假设我有一个包含一个或多个元组的列表:
[0, 2, (1, 2), 5, 2, (3, 5)]
什么是摆脱元组的最好方法,以便它只是一个int列表?
[0, 2, 1, 2, 5, 2, 3, 5]
答案 0 :(得分:4)
使用嵌套列表理解:
>>> lst = [0, 2, (1, 2), 5, 2, (3, 5)]
>>> [y for x in lst for y in (x if isinstance(x, tuple) else (x,))]
[0, 2, 1, 2, 5, 2, 3, 5]
答案 1 :(得分:3)
解决方案之一(使用itertools.chain):
>>> from itertools import chain
>>> l = [0, 2, (1, 2), 5, 2, (3, 5)]
>>> list(chain(*(i if isinstance(i, tuple) else (i,) for i in l)))
[0, 2, 1, 2, 5, 2, 3, 5]
答案 2 :(得分:1)
def untuppleList(lst):
def untuppleList2(x):
if isinstance(x, tuple):
return list(x)
else:
return [x]
return [y for x in lst for y in untuppleList2(x)]
然后你可以untuppleList([0, 2, (1, 2), 5, 2, (3, 5)])
。
答案 3 :(得分:1)
更通用的递归解决方案,应该适用于任何可迭代的(字符串除外)和任何深度的元素:
import collections
def flatten(iterable):
results = []
for i in iterable:
if isinstance(i, collections.Iterable) and not isinstance(i, basestring):
results.extend(flatten(i))
else:
results.append(i)
return results
用法:
>>> flatten((1, 2, (3, 4), ('happy')))
[1, 2, 3, 4, 'happy']
>>> flatten((1, 2, (3, 4, (5, 6)), ('happy'), {'foo': 'bar', 'baz': 123}))
[1, 2, 3, 4, 5, 6, 'happy', 'foo', 'baz']
答案 4 :(得分:1)
from funcy import flatten
flat_list = flatten(your_list)
您还可以查看its implementation。