Python中如何将多个列表合并成一个大列表?
a = [1]
b = [2]
c = [3]
d = []
如何合并成 d = [[1], [2], [3]]?
Python中如何将多个列表合并成一个大列表?
17 回复
直接使用 + 运算符或者 extend() 方法就行。
# 方法1:使用 + 运算符
list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [True, False]
combined_list = list1 + list2 + list3
print(combined_list) # 输出:[1, 2, 3, 'a', 'b', True, False]
# 方法2:使用 extend() 方法(原地修改第一个列表)
list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [True, False]
list1.extend(list2)
list1.extend(list3)
print(list1) # 输出:[1, 2, 3, 'a', 'b', True, False]
如果列表很多,用 itertools.chain() 更高效,尤其适合处理大量数据或者迭代器。
import itertools
lists = [[1, 2], ['a', 'b'], [True, False]]
combined_list = list(itertools.chain(*lists))
print(combined_list) # 输出:[1, 2, 'a', 'b', True, False]
总结:小列表直接用+,要改原列表就用extend(),列表多或大就用itertools.chain()。
d = [l for l in [a, b, c, d] if len(l) > 0]
没看懂,d = [a, b, c] 不行吗
可以 厉害
d = [a, b, c]
过滤掉 d 为[],然后合并成个列表?
list(filter(None,[a,b,c,d]))
[l for l in [a, b, c, d] if l]
这样貌似快一些
#2
是的 len([]) > 0 这不 pythonic
来个题外的,如果是要把 a、b、c 合并成[1, 2, 3],那么可以用 d=sum([a, b, c], [])
时间复杂度会不会太高了
d = a + b + c
嗯,我举措例子了。。。。。。。应该是展开的例子。。。。。。
>>> d = [[1,2,3], [4,5], [6,7]]
>>> sum(d, [])
[1, 2, 3, 4, 5, 6, 7]
[a,b,c]直接引用应该是最快的吧
from itertools import chain
d = list(chain(a, b, c))


