簡體   English   中英

如何在Python中展平嵌套元組列表?

[英]How to flatten a list of nested tuples in Python?

我有一個看起來像這樣的元組列表:

[('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]

我想把它變成這個:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

最恐怖的方式是什么?

規范的非展平配方調整為僅在值中有元組時不展平

def flatten(l):
    for el in l:
        if isinstance(el, tuple) and any(isinstance(sub, tuple) for sub in el):
            for sub in flatten(el):
                yield sub
        else:
            yield el

這只會解包元組,並且只有在其中有其他元組時:

>>> sample = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
>>> list(flatten(sample))
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

單行,使用列表理解:

l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]

result = [z for y in (x if isinstance(x[0],tuple) else [x] for x in l) for z in y]

print(result)

收益率:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

如果元素不是元組的元組,那么人為地創建一個列表,然后展平所有工作。 為了避免創建單個元素列表[x](x for _ in range(1))也可以完成這項工作(雖然看起來很笨重)

限制:不能處理超過1級的嵌套。 在這種情況下,必須編寫更復雜/遞歸的解決方案(檢查Martijn的答案 )。

一行解決方案是使用itertools.chain

>>> l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
>>> from itertools import chain
>>> [*chain.from_iterable(x if isinstance(x[0], tuple) else [x] for x in l)]
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM