I am very new to python and i was stuck with this. I need to create a list of lists that is
formed from this list c
: ['asdf','bbnm','rtyu','qwer']
.
I need to create something like this:
b
: [['a','s','d','f'],['b','b','n','m'],['r','t','y','u'],['q','w','e','r']]
I tried using a for
-loop, but it is not working out. I don't know what mistake I am making.
3 Answers 3
You can use a list comprehension with list()
:
>>> c = ['asdf','bbnm','rtyu','qwer']
>>>
>>> b = [list(s) for s in c]
>>> b
[['a', 's', 'd', 'f'], ['b', 'b', 'n', 'm'], ['r', 't', 'y', 'u'], ['q', 'w', 'e', 'r']]
Notice that calling list()
with a string argument returns a list containing the characters of that string:
>>> list('abc')
['a', 'b', 'c']
What we're doing above is applying this to every element of the list via the comprehension.
Comments
Use map function.
>>> a= ['asdf','bbnm','rtyu','qwer']
>>> map(list ,a )
[['a', 's', 'd', 'f'], ['b', 'b', 'n', 'm'], ['r', 't', 'y', 'u'], ['q', 'w', 'e', 'r']]
>>>
Comments
You could do something that's easier to understand:
b = []
for x in c:
list(x).append(b)
[list(s) for s in c]
should work.list(x)
converts any sequence into a list of its elements, and astr
is a sequence of its characters. The surrounding stuff is a list comprehension.list
?