2013-02-11 74 views
21

鑑於lists = [['hello'], ['world', 'foo', 'bar']]Python列表理解加入列表清單

如何將其轉換爲單個字符串列表?

combinedLists = ['hello', 'world', 'foo', 'bar']

+0

我知道我可以通過使用嵌套循環做了很長的路要走,但我想知道,如果有一個一行做一樣。 – congusbongus 2013-02-11 07:33:41

回答

59
lists = [['hello'], ['world', 'foo', 'bar']] 
combined = [item for sublist in lists for item in sublist] 

或者:

import itertools 

lists = [['hello'], ['world', 'foo', 'bar']] 
combined = list(itertools.chain.from_iterable(lists)) 
+1

雖然第一選擇看起來更好,在我看來。使用itertools要快得多。這個答案很好。 – 2013-02-11 07:40:42

3
from itertools import chain 

combined = [['hello'], ['world', 'foo', 'bar']] 
single = [i for i in chain.from_iterable(combined)]