如果我有
colours = [ "red", "green", "yellow"]
animals = [ "mouse", "tiger", "elephant" ]
coloured_animals = [ (x,y) for x in colours for y in things ]
我需要添加什么以便列表理解返回 ("红色","鼠标"),("绿色","老虎"),("黄色", " elephant")而不是所有配对?
答案 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')]
>>>