English 中文(简体)
Python 使用在列表内加列理解
原标题:Python using enumerate inside list comprehension

假设我有一个像这样的名单:

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

要将值与索引一起打印,我可以使用 Python s 数字 函数这样的功能

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

当我试图在 < code> list 理解 中使用它时, 它给了我这个错误

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

因此,我的问题是:使用清单中列举的正确理解方式是什么?

最佳回答

尝试此 :

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

您需要将 i, j 放到一个图普里, 以便列表理解工作。 或者, 如果 numberate() already 返回一个图普, 您可以直接返回它而不先解开它 :

[pair for pair in enumerate(mylist)]

无论哪种方式,返回的结果都与预期的相同:

> [(0,  a ), (1,  b ), (2,  c ), (3,  d )]
问题回答

要非常清楚,这与 numberate 无关,与列表理解语法无关。

此列表理解返回一个图例列表 :

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

此处列出一个命令列表 :

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

列表列表 :

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

语法错误 :

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

这与(IMHO)不一致, 也与字典理解语法混为一谈:

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

和一套图腾:

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

正如奥斯卡·洛佩斯所说,你可以直接通过所列举的图普:

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

或者,如果你不坚持使用列表理解:

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

如果您使用长列表, 列表理解速度似乎更快, 更不用提更可读了 。

~$ 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

有个方法可以做到:

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

或者,你可以做:

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

您错误的原因是您丢失了 i j 周围的( ), 以使其成为图普尔 。

说清楚一点,关于图普尔斯。

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

所有伟大的回答者。我知道这里的问题 具体到列举,但如何 像这样的东西,只是另一个角度

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

如果一个人不得不在业绩方面同时重复多个列表,它就会变得更强大。

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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签