在python中合并子列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14278664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merging sublists in python
提问by thclpr
Possible Duplicate:
Flattening a shallow list in Python
Making a flat list out of list of lists in Python
Merge two lists in python?
可能的重复:
在 Python 中展平一个浅列表 从 Python 中的列表列表中
制作一个平面列表 在 Python 中
合并两个列表?
Fast and simple question:
快速而简单的问题:
How do i merge this.
我如何合并这个。
[['a','b','c'],['d','e','f']]
to this:
对此:
['a','b','c','d','e','f']
采纳答案by will
list concatenation is just done with the +operator.
列表连接只是用+操作符完成的。
so
所以
total = []
for i in [['a','b','c'],['d','e','f']]:
total += i
print total
回答by Sibi
This would do:
这会做:
a = [['a','b','c'],['d','e','f']]
reduce(lambda x,y:x+y,a)
回答by Hui Zheng
Try:
尝试:
sum([['a','b','c'], ['d','e','f']], [])
Or longer but faster:
或者更长但更快:
[i for l in [['a', 'b', 'c'], ['d', 'e', 'f']] for i in l]
Or use itertools.chainas @AshwiniChaudhary suggested:
或者itertools.chain按照@AshwiniChaudhary 的建议使用:
list(itertools.chain(*[['a', 'b', 'c'], ['d', 'e', 'f']]))
回答by Harpal
mergedlist = list_letters[0] + list_letters[1]
This assumes you have a list of a static length and you always want to merge the first two
这假设您有一个静态长度的列表,并且您总是希望合并前两个
>>> list_letters=[['a','b'],['c','d']]
>>> list_letters[0]+list_letters[1]
['a', 'b', 'c', 'd']
回答by Ketouem
Using list comprehension:
使用列表理解:
ar = [['a','b','c'],['d','e','f']]
concat_list = [j for i in ar for j in i]
回答by Kiwisauce
Try the "extend" method of a list object:
尝试列表对象的“扩展”方法:
>>> res = []
>>> for list_to_extend in range(0, 10), range(10, 20):
res.extend(list_to_extend)
>>> res
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Or shorter:
或更短:
>>> res = []
>>> map(res.extend, ([1, 2, 3], [4, 5, 6]))
>>> res
[1, 2, 3, 4, 5, 6]

