以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。
如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?
在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。
以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。
如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?
在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。
当前回答
如果你有一个Numpy Array A:
a = np.array([[1,2], [3,4]])
a.flatten('C')
生产:
[1, 2, 3, 4]
np.flatten 也接受其他参数:
C: F A K
有关参数的详细信息可在这里找到。
其他回答
matplotlib.cbook.flatten() 将为粘贴列表工作,即使它们比示例更深地粘贴。
import matplotlib
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
print(list(matplotlib.cbook.flatten(l)))
l2 = [[1, 2, 3], [4, 5, 6], [7], [8, [9, 10, [11, 12, [13]]]]]
print(list(matplotlib.cbook.flatten(l2)))
结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
这比 underscore 快 18 倍。
Average time over 1000 trials of matplotlib.cbook.flatten: 2.55e-05 sec
Average time over 1000 trials of underscore._.flatten: 4.63e-04 sec
(time for underscore._)/(time for matplotlib.cbook) = 18.1233394636
def flatten_array(arr):
result = []
for item in arr:
if isinstance(item, list):
for num in item:
result.append(num)
else:
result.append(item)
return result
print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))
// output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
使用 functools.reduce,将积累的列表 xs 添加到下列列表 ys:
from functools import reduce
xss = [[1,2,3], [4,5,6], [7], [8,9]]
out = reduce(lambda xs, ys: xs + ys, xss)
出口:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
使用 operator.concat 的更快方法:
from functools import reduce
import operator
xss = [[1,2,3], [4,5,6], [7], [8,9]]
out = reduce(operator.concat, xss)
出口:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
对于包含多个列表的列表,这里是一个重复的解决方案,为我工作,我希望它是正确的:
# Question 4
def flatten(input_ls=[]) -> []:
res_ls = []
res_ls = flatten_recursive(input_ls, res_ls)
print("Final flatten list solution is: \n", res_ls)
return res_ls
def flatten_recursive(input_ls=[], res_ls=[]) -> []:
tmp_ls = []
for i in input_ls:
if isinstance(i, int):
res_ls.append(i)
else:
tmp_ls = i
tmp_ls.append(flatten_recursive(i, res_ls))
print(res_ls)
return res_ls
flatten([0, 1, [2, 3], 4, [5, 6]]) # test
flatten([0, [[[1]]], [[2, 3], [4, [[5, 6]]]]])
出口:
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
Final flatten list solution is:
[0, 1, 2, 3, 4, 5, 6]
[0, 1]
[0, 1]
[0, 1]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
Final flatten list solution is:
[0, 1, 2, 3, 4, 5, 6]
def flatten(itr):
for x in itr:
try:
yield from flatten(x)
except TypeError:
yield x
使用:这是一个发电机,通常你想将它插入一个不可分割的构建器,如列表()或<<<<<<<<或使用它在一个为旋转。
这个解决方案的好处是:
工作任何类型的无缝(即使是未来的!)工作任何组合和深度的无缝工作,如果顶级包含无依赖物品,快速和高效(你可以平滑无缝的部分,没有浪费时间的剩余部分你不需要)多样性(你可以使用它来构建一个无缝的你的选择或在旋转)
注:由于所有 iterables 都是浮动的,所以线条分为单个字符的序列. 如果您不喜欢/不喜欢这种行为,您可以使用下列版本,从浮动的 iterables 如线条和比特中进行过滤:
def flatten(itr):
if type(itr) in (str,bytes):
yield itr
else:
for x in itr:
try:
yield from flatten(x)
except TypeError:
yield x