将列表组合成具有特定配对的元组

时间:2016-06-07 23:43:17

标签: python list tuples

如果我有

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

我需要添加什么以便列表理解返回 ("红色","鼠标"),("绿色","老虎"),("黄色", " elephant")而不是所有配对?

2 个答案:

答案 0 :(得分:3)

python有这个

的内置函数zip
>>> colours = [ "red", "green", "yellow"]
>>> animals = [ "mouse", "tiger", "elephant" ]
>>> zip(colours, animals)
[('red', 'mouse'), ('green', 'tiger'), ('yellow', 'elephant')]

答案 1 :(得分: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')]
>>> 
相关问题