4 回答

TA贡献1828条经验 获得超6个赞
您可以使用chain.from_iterable:
from itertools import chain
a = [[0, 1], [2, 3], [4, 5], [6, 7]]
result = list(chain.from_iterable(a))
print(result)
输出
[0, 1, 2, 3, 4, 5, 6, 7]

TA贡献1883条经验 获得超3个赞
您可以抓取每个子列表并添加到新列表中。
new_ldata = []
for sublist in ldata:
new_ldata += sublist

TA贡献1802条经验 获得超10个赞
您可以为此使用 numpy concatenate
import numpy as np
x = [[1,1],[2,2,2],[3],[4,4,4,4]]
concated_x = np.concatenate(x) # now in numpy array form
concated_x = list(concated_x) # if you want it back to a list form

TA贡献2051条经验 获得超10个赞
如果您的列表不太长,请保持简单:
>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> sum(a, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
我做了一些计时测量:
>>> timeit.timeit('sum([[1,2,3],[4,5,6],[7,8,9]], [])')
6.547808872535825
>>> timeit.timeit('reduce(lambda a, c: a + c, [[1,2,3],[4,5,6],[7,8,9]], [])', setup="from functools import reduce")
10.435796303674579
列表越多,列表越长,解决方案的chain性能会更好:
a = [list(range(20)) for x in range(30)]
def test_sum():
return sum(a, [])
def test_chain():
return list(itertools.chain.from_iterable(a))
def test_add():
result = []
for i in a:
result += i
return result
def test_list_comprehension():
return [x for l in a for x in l]
print(timeit.timeit(test_sum), timeit.timeit(test_chain), timeit.timeit(test_add), timeit.timeit(test_list_comprehension))
产量
18.778313734044787 7.5882537689758465 2.5082976589910686 13.912770285038278
这表明将数组与一个短函数相加也很不错。
添加回答
举报