我有一个列表如下所示:
a = [['he', 'goes'],
['he does'],
['one time'],
[('he','is'), ('she', 'went'), ('they', 'are')],
['he', 'must'],
['they use']]
我试图将列表展平,以便它只是一个没有元组的列表列表。例如:
a = [['he', 'goes'],
['he does'],
['one time'],
['he','is'],
['she', 'went'],
['they', 'are'],
['he', 'must'],
['they use']]
我尝试过使用itertools.chain.from_iterable()
,但会将所有嵌套列表展平。
答案 0 :(得分:6)
b = []
for x in a:
if isinstance(x[0], tuple):
b.extend([list(y) for y in x])
else:
b.append(x)
答案 1 :(得分:6)
使用yield from和python3:
from collections import Iterable
def conv(l):
for ele in l:
if isinstance(ele[0], Iterable) and not isinstance(ele[0],str):
yield from map(list,ele)
else:
yield ele
print(list(conv(a)))
[['he', 'goes'], ['he does'], ['one time'], ['he', 'is'], ['she', 'went'], ['they', 'are'], ['he', 'must'], ['they use']]
对于python2
,您可以遍历itertools.imap对象:
from collections import Iterable
from itertools import imap
def conv(l):
for ele in l:
if isinstance(ele[0], Iterable) and not isinstance(ele[0],basestring):
for sub in imap(list, ele):
yield sub
else:
yield ele
print(list(conv(a)))
如果您有嵌套元组,则需要添加更多逻辑。
答案 2 :(得分:5)
这解决了你的例子:
a = [list(strings) for sublist in a for strings in
([sublist] if isinstance(sublist[0], str) else sublist)]
对于已经是字符串列表的每个子列表,只需使用该子列表。否则遍历该子列表。
这还不够,或者您的实际数据是否更复杂?