One of solutions (using 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]
题
Say I have a list with one or more tuples in it:
[0, 2, (1, 2), 5, 2, (3, 5)]
What's the best way to get rid of the tuples so that it's just an int list?
[0, 2, 1, 2, 5, 2, 3, 5]
解决方案
One of solutions (using 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]
其他提示
Using a nested list comprehension:
>>> 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)]
Then you can do untuppleList([0, 2, (1, 2), 5, 2, (3, 5)])
.
A more general recursive solution, that should apply to any iterable (except strings) and any depth of elements:
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
And usage:
>>> 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']
You can use flatten function from my funcy library:
from funcy import flatten
flat_list = flatten(your_list)
You can also peek at its implementation.