I try to make flat list. Now I have list:
L=['aa',['bb','cc']]
and I try:
L=['aa',['bb','cc']]
new=[]
for i in L:
print i
new+=i
print new
and I got:
'aa'
['bb','cc']
['a','a','bb','cc']
Why in print i=0 = 'aa'
and in new+=ii=0
is only 'a'?
How i could get list ['aa','bb','cc']
?
In general, meaning when you don't know the depth of the original list, this should work:
L=['aa',['bb','cc', ['dd', 'ee']], 'ff']
new = []
for l_item in L:
stack = [ l_item ]
while stack:
s_item = stack.pop(0)
if isinstance(s_item, list):
stack += [ x for x in s_item ]
else:
new.append(s_item)
print new
This gives:
['aa', 'bb', 'cc', 'dd', 'ee', 'ff']
Well, don't forget that strings are iterable in Python.
>>> new = []
>>> new += 'aa'
>>> print new
['a', 'a']
To be sure of adding what you want, you can proceed this way:
>>> L = ['aa',['bb','cc']]
>>> new = []
>>> for e in L:
... new.extend(e if type(e) == list else (e,))
>>> print new
['aa', 'bb', 'cc']
Seriously,
PS You can look at this post ... for more information.
This happens because you iterate over 'aa'
, basically treating it like it was ['a', 'a']
.
If you want to avoid iterating over strings, you can look at the type:
for i in L:
if isinstance(i, list):
new += i
else:
new.append(i)
See this question for more details and how to do it recursively:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.