简体   繁体   English

Python使用枚举内部列表理解

[英]Python using enumerate inside list comprehension

Lets suppose I have a list like this: 假设我有一个这样的列表:

mylist = ["a","b","c","d"]

To get the values printed along with their index I can use Python's enumerate function like this 要获得打印的值及其索引,我可以使用Python的enumerate函数,如下所示

>>> for i,j in enumerate(mylist):
...     print i,j
...
0 a
1 b
2 c
3 d
>>>

Now, when I try to use it inside a list comprehension it gives me this error 现在,当我尝试在list comprehension使用它时,出现了这个错误

>>> [i,j for i,j in enumerate(mylist)]
  File "<stdin>", line 1
    [i,j for i,j in enumerate(mylist)]
           ^
SyntaxError: invalid syntax

So, my question is: what is the correct way of using enumerate inside list comprehension? 所以,我的问题是:在列表理解中使用枚举的正确方法是什么?

Try this: 尝试这个:

[(i, j) for i, j in enumerate(mylist)]

You need to put i,j inside a tuple for the list comprehension to work. 您需要将i,j放入一个元组中,以使列表理解起作用。 Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first: 另外,假设enumerate() 已经返回一个元组,则可以直接将其返回,而无需先将其拆包:

[pair for pair in enumerate(mylist)]

Either way, the result that gets returned is as expected: 无论哪种方式,返回的结果都是预期的:

> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Just to be really clear, this has nothing to do with enumerate and everything to do with list comprehension syntax. 确切地说,这与enumerate无关,与列表理解语法无关。

This list comprehension returns a list of tuples: 此列表推导返回一个元组列表:

[(i,j) for i in range(3) for j in 'abc']

this a list of dicts: 这是字典列表:

[{i:j} for i in range(3) for j in 'abc']

a list of lists: 列表清单:

[[i,j] for i in range(3) for j in 'abc']

a syntax error: 语法错误:

[i,j for i in range(3) for j in 'abc']

Which is inconsistent (IMHO) and confusing with dictionary comprehensions syntax: 不一致(IMHO)并与字典理解语法混淆:

>>> {i:j for i,j in enumerate('abcdef')}
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

And a set of tuples: 和一组元组:

>>> {(i,j) for i,j in enumerate('abcdef')}
set([(0, 'a'), (4, 'e'), (1, 'b'), (2, 'c'), (5, 'f'), (3, 'd')])

As Óscar López stated, you can just pass the enumerate tuple directly: 正如ÓscarLópez所说,您可以直接通过枚举元组:

>>> [t for t in enumerate('abcdef') ] 
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]

Or, if you don't insist on using a list comprehension: 或者,如果您不坚持使用列表理解:

>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

If you're using long lists, it appears the list comprehension's faster, not to mention more readable. 如果您使用的是长列表,则列表理解似乎会更快,更不用说可读性了。

~$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))"
1000000 loops, best of 3: 1.61 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]"
1000000 loops, best of 3: 0.978 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[t for t in enumerate(mylist)]"
1000000 loops, best of 3: 0.767 usec per loop

Here's a way to do it: 这是一种方法:

>>> mylist = ['a', 'b', 'c', 'd']
>>> [item for item in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Alternatively, you can do: 或者,您可以执行以下操作:

>>> [(i, j) for i, j in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

The reason you got an error was that you were missing the () around i and j to make it a tuple. 出现错误的原因是,您错过了ij周围的()使其成为一个元组。

明确说明元组。

[(i, j) for (i, j) in enumerate(mylist)]

All great answer guys. 所有人都很好回答。 I know the question here is specific to enumeration but how about something like this, just another perspective 我知道这里的问题是针对枚举的,但是这样的话,又是另一个角度

from itertools import izip, count
a = ["5", "6", "1", "2"]
tupleList = list( izip( count(), a ) )
print(tupleList)

It becomes more powerful, if one has to iterate multiple lists in parallel in terms of performance. 如果必须在性能方面并行迭代多个列表,它将变得更加强大。 Just a thought 只是一个想法

a = ["5", "6", "1", "2"]
b = ["a", "b", "c", "d"]
tupleList = list( izip( count(), a, b ) )
print(tupleList)

如果mylist = [“ a”,“ b”,[“ x”,“ y”],“ d”],该如何处理

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

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