假设我有一个包含一个或多个元组的列表:
什么是消除元组以使其成为整数列表的最佳方法?
[0, 2, (1, 2), 5, 2, (3, 5)]
什么是消除元组以使其成为整数列表的最佳方法?
[0, 2, 1, 2, 5, 2, 3, 5]
[0, 2, (1, 2), 5, 2, (3, 5)]
[0, 2, 1, 2, 5, 2, 3, 5]
以下是其中一种解决方案(使用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]
使用嵌套列表推导:
>>> 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]
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)])
。
更通用的递归解决方案,适用于任何可迭代对象(除了字符串)和任何深度的元素:
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']