可能重複:
Flattening a shallow list in Python
Making a flat list out of list of lists in Python
Merge two lists in python?合併子列表
快速和簡單的問題:
我怎麼合併這一點。
[['a','b','c'],['d','e','f']]
這樣:
['a','b','c','d','e','f']
可能重複:
Flattening a shallow list in Python
Making a flat list out of list of lists in Python
Merge two lists in python?合併子列表
快速和簡單的問題:
我怎麼合併這一點。
[['a','b','c'],['d','e','f']]
這樣:
['a','b','c','d','e','f']
連接列表只是與+
操作完成。
所以
total = []
for i in [['a','b','c'],['d','e','f']]:
total += i
print total
這會做:
a = [['a','b','c'],['d','e','f']]
reduce(lambda x,y:x+y,a)
嘗試:
sum([['a','b','c'], ['d','e','f']], [])
或更長的時間,但速度更快:
[i for l in [['a', 'b', 'c'], ['d', 'e', 'f']] for i in l]
或者使用itertools.chain
爲@AshwiniChaudhary建議:
list(itertools.chain(*[['a', 'b', 'c'], ['d', 'e', 'f']]))
'sum()'不應該用於這樣的事情。作爲[文件](http://docs.python.org/2/library/functions.html#sum)說:**要連接的一系列iterables的,可以考慮使用itertools.chain()** –
mergedlist = list_letters[0] + list_letters[1]
這裏假設你有一個靜態長度的列表,你總是要合併前兩個
>>> list_letters=[['a','b'],['c','d']]
>>> list_letters[0]+list_letters[1]
['a', 'b', 'c', 'd']
使用列表理解:
ar = [['a','b','c'],['d','e','f']]
concat_list = [j for i in ar for j in i]
這是最快的方式,fwiw。就CPU週期而言。 –
完全是最好的方式,因爲它是最緊湊的。但它是如何工作的? –
嘗試列表對象的「擴展」方法:
>>> 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]
或更短:
>>> res = []
>>> map(res.extend, ([1, 2, 3], [4, 5, 6]))
>>> res
[1, 2, 3, 4, 5, 6]
這是最好的解決方案,因爲它是最簡單的。 +1。但是,您可以簡單地執行: 'new_list = old_list1 + old_list2'。你的同樣的事情,但你不需要把它們放在列表中的列表。 –
是的,我只是想讓它適用於任意列表。我從那以後就知道你可以做一些像sum([],[list1,list2,list3])的東西,並且由於sum調用+運算符,對於'[]'是連接運算符,它會將它們全部加入爲你。 – will