2016-06-07 50 views
0

如果我有合併列表到元組與特定的配對

colours = [ "red", "green", "yellow"] 
animals = [ "mouse", "tiger", "elephant" ] 
coloured_animals = [ (x,y) for x in colours for y in things ] 

什麼我需要添加以便列表理解返回 (「紅」,「鼠標」),(「綠色」,「虎虎生威「),(」黃色「,」大象「)而不是所有配對?

回答

3

Python有內置的功能zip這個

>>> colours = [ "red", "green", "yellow"] 
>>> animals = [ "mouse", "tiger", "elephant" ] 
>>> zip(colours, animals) 
[('red', 'mouse'), ('green', 'tiger'), ('yellow', 'elephant')] 
1

您可以使用內置的功能zip,但如果你想解決您的列表解析,這裏是你會怎麼做,前提是len(colours) <= len(animals)

>>> coloured_animals = [(colours[x], animals[x]) for x in range(len(colours))] 
>>> coloured_animals 
[('red', 'mouse'), ('green', 'tiger'), ('yellow', 'elephant')] 
>>>