简体   繁体   English

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

[英]enumerate is iterating of letters of strings in a list instead of elements

I'm trying to use enumerate to iterate of a list and store the elements of the list as well as use the index to grab the index of another list the same size.我正在尝试使用enumerate来迭代列表并存储列表的元素以及使用索引来获取另一个相同大小的列表的索引。

Using a silly example:使用一个愚蠢的例子:

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

Instead of producing tuples of each element of both lists.而不是生成两个列表的每个元素的元组。 It produces tuples by letter.它按字母生成元组。 Is there a way to do this but get the elements of each list rather than each letter?有没有办法做到这一点,但获取每个列表的元素而不是每个字母? I know there is likely a better more pythonic way of accomplishing this same task, but I'm specifically looking to do it this way.我知道可能有更好的 Pythonic 方式来完成同样的任务,但我特别希望这样做。

enumerate() is doing no such thing. enumerate()没有做这样的事情。 You are pairing up the letters here:你在这里配对字母:

y = zip(name[count], i)

For example, for the first element in animal , count is 0 and i is set to 'cat' .例如,对于animal的第一个元素, count0并且i设置为'cat' name[0] is 'george' , so you are asking Python to zip() together 'george' and 'cat' : name[0]'george' ,所以你要求 Python zip() 'george''cat'

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

This is capped at the shorter wordlength.这以较短的字长为上限。

If you wanted a tuple, just use:如果你想要一个元组,只需使用:

y = (name[count], i)

and then append that to your x list:然后附加到您的x列表中:

x.append(y)

You could use zip() instead of enumerate() to create your pairings:可以使用zip()而不是enumerate()来创建配对:

x = zip(name, animal)

without any loops required:无需任何循环:

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

When you use zip() it actually creates a list of tuples of corresponding elements at each index.当您使用zip()它实际上会在每个索引处创建相应元素的元组列表。

So when you provide strings as the input, it provides the result as list of tuples at each character.因此,当您提供strings作为输入时,它会以每个字符的元组列表的形式提供结果。 Example -例子 -

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

This is what you are doing, when you iterate over each element in the list and use zip.当您遍历列表中的每个元素并使用 zip 时,这就是您正在做的事情。

Instead , you should directly use zip , without iterating over the elements of the list.相反,您应该直接使用zip ,而不是遍历列表的元素。

Example -例子 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM