枚举是迭代列表中字符串的字母而不是元素

enumerate is iterating of letters of strings in a list instead of elements

我正在尝试使用 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中的第一个元素,count0并且i设置为'cat'name[0]'george',所以你要求 Python 和 zip() 一起 'george''cat':

>>> 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')]

当您使用 zip() 时,它实际上会在每个索引处创建相应元素的元组列表。

因此,当您提供 strings 作为输入时,它会以每个字符处的元组列表形式提供结果。示例 -

>>> zip('cat','george')
[('c', 'g'), ('a', 'e'), ('t', 'o')]

当您遍历列表中的每个元素并使用 zip 时,这就是您正在做的事情。

相反,您应该直接使用 zip,而不遍历列表的元素。

例子-

>>> animal = ['cat', 'dog', 'fish' , 'monkey']
>>> name = ['george', 'steve', 'john', 'james']
>>> zip(animal,name)
[('cat', 'george'), ('dog', 'steve'), ('fish', 'john'), ('monkey', 'james')]