2016-01-27 22 views
1

我正在Python中編寫for循環,我想遍歷對象的單個對象和扁平列表(或元組)的混合。遍歷python中的單值和迭代的組合

例如:

a = 'one' 
b = 'two' 
c = [4, 5] 
d = (10, 20, 30) 

我想遍歷所有的這些在for循環中。我想這樣的語法將優雅:

for obj in what_goes_here(a, b, *c, *d): 
    # do something with obj 

itertools尋找what_goes_here,我沒有看到任何東西,但我覺得我必須缺少明顯的東西!

我發現最近的是鏈條,但我想知道是否有任何東西存在,這將使我的示例保持不變(僅替換what_goes_here)。

+0

什麼是你的迭代輸出? – haifzhan

+0

您將遇到的問題是字符串是可迭代的,所以您的字符串可能會被拆分爲單個字符。我想你可能需要爲此編寫自己的函數。 –

+1

'''l = [a,b,c,d]''' '''list(itertools.chain(* [x if is not isinstance(x,str)else [x] for x in l])) ''' –

回答

1

你可以這樣做,但是你必須使用Python 3.5或更高版本來擴展解壓縮語法。將所有參數放入容器中(如tuple),然後將該容器發送到itertools.chain

>>> import itertools 
>>> a = 'one' 
>>> b = 'two' 
>>> c = [4, 5] 
>>> d = (10, 20, 30) 
>>> list(itertools.chain((a, b, *c, *d))) 
['one', 'two', 4, 5, 10, 20, 30] 
>>> list(itertools.chain((a, *c, b, *d))) 
['one', 4, 5, 'two', 10, 20, 30] 
>>> list(itertools.chain((*a, *c, b, *d))) 
['o', 'n', 'e', 4, 5, 'two', 10, 20, 30] 
0
import collections, itertools 

a = 'one' 
b = 'two' 
c = [4, 5] 
d = (10, 20, 30) 
e = 12 

l = [a, b, c, d, e] 

newl = list(itertools.chain(*[x if isinstance(x, collections.Iterable) and not isinstance(x, str) else [x] for x in l]))