我正在尝试使用 enumerate 迭代列表并存储列表的元素,以及使用索引获取另一个相同大小的列表的索引。
使用一个愚蠢的例子:
animal = ['cat', 'dog', 'fish' , 'monkey']
name = ['george', 'steve', 'john', 'james']
x = []
for count, i in enumerate(animal):
y = zip(name[count], i)
x = x +y
而不是生成两个列表的每个元素的元组。它按字母生成元组。有没有办法做到这一点,但获取每个列表的元素而不是每个字母?我知道可能有更好的 Pythonic 方式来完成同样的任务,但我特别希望以这种方式完成。
请您参考如下方法:
enumerate() 没有做这样的事情。你在这里配对字母:
y = zip(name[count], i)
例如,对于animal中的第一个元素,count为0,i设置为'猫'。 name[0] 是 'george',因此您要求 Python zip() 一起 'george'和“猫”:
>>> zip('george', 'cat')
[('g', 'c'), ('e', 'a'), ('o', 't')]
这以较短的字长为上限。
如果你想要一个元组,只需使用:
y = (name[count], i)
然后将其附加到您的x列表中:
x.append(y)
您可以使用zip() 而不是enumerate() 来创建配对:
x = zip(name, animal)
无需任何循环:
>>> animal = ['cat', 'dog', 'fish' , 'monkey']
>>> name = ['george', 'steve', 'john', 'james']
>>> zip(name, animal)
[('george', 'cat'), ('steve', 'dog'), ('john', 'fish'), ('james', 'monkey')]
