具有元组列表的列表列表

GNM*_*O11 2 python tuples list

我有一个列表列表,如下所示:

a = [['he', 'goes'],
     ['he does'],
     ['one time'],
     [('he','is'), ('she', 'went'), ('they', 'are')],
     ['he', 'must'],
     ['they use']]
Run Code Online (Sandbox Code Playgroud)

我试图压缩列表,使它只是一个没有元组的列表列表.例如:

a = [['he', 'goes'],
     ['he does'],
     ['one time'],
     ['he','is'], 
     ['she', 'went'],
     ['they', 'are'],
     ['he', 'must'],
     ['they use']]
Run Code Online (Sandbox Code Playgroud)

我尝试过使用itertools.chain.from_iterable()平坦化所有嵌套列表.

pok*_*oke 6

b = []
for x in a:
    if isinstance(x[0], tuple):
        b.extend([list(y) for y in x])
    else:
        b.append(x)
Run Code Online (Sandbox Code Playgroud)


Pad*_*ham 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']]
Run Code Online (Sandbox Code Playgroud)

因为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)))
Run Code Online (Sandbox Code Playgroud)

如果您有嵌套元组,则需要添加更多逻辑.


Ste*_*ann 5

这解决了你的例子:

a = [list(strings) for sublist in a for strings in
     ([sublist] if isinstance(sublist[0], str) else sublist)]
Run Code Online (Sandbox Code Playgroud)

对于已经是字符串列表的每个子列表,只需使用该子列表.否则迭代该子列表.

这还不够,或者您的实际数据更复杂?