我觉得我错过了一些明显的东西,但它就是......我想从:
lst = [[0, 1, 3, 7, 8, 11, 12], [8, 0, 1, 2, 3, 14], 2]
至:
output = [0, 1, 3, 7, 8, 11, 12, 8, 0, 1, 2, 3, 14, 2]
我可以使用 for 循环来做到这一点,例如:
output = []
for l in lst:
if hasattr(l, '__iter__'):
output.extend(l)
else:
output.append(l)
也许 for 循环很好,但感觉应该有一种更优雅的方式来做到这一点......尝试用 numpy 来做这件事似乎更令人费解,因为不容易处理参差不齐的数组......所以你可以' t(例如):
output = np.asanyarray(lst).flatten().tolist()
提前致谢。
更新:
这是我对@TJ 和@Ashwini 提供的两种方法的比较——感谢两者!
In [5]: %paste
from itertools import chain
from collections import Iterable
lis = [[0, 1, 3, 7, 8, 11, 12], [8, 0, 1, 2, 3, 14], 2]
def solve(lis):
for x in lis:
if isinstance(x, Iterable) and not isinstance(x, basestring):
yield x
else:
yield [x]
%timeit list(chain.from_iterable(solve(lis)))
%timeit [a for x in lis for a in (x if isinstance(x, Iterable) and not isinstance(x,basestring) else [x])]
## -- End pasted text --
100000 loops, best of 3: 10.1 us per loop
100000 loops, best of 3: 8.12 us per loop
更新2:
...
lis = lis *10**5
%timeit list(chain.from_iterable(solve(lis)))
%timeit [a for x in lis for a in (x if isinstance(x, Iterable) and not isinstance(x,basestring) else [x])]
## -- End pasted text --
1 loops, best of 3: 699 ms per loop
1 loops, best of 3: 698 ms per loop