如何在Python中显示列表元素的索引?

时间:2016-01-12 21:11:35

标签: python list python-3.x position

我有一份家庭作业。我有以下代码

hey = ["lol", "hey","water","pepsi","jam"]

for item in hey:
    print(item)

我是否在项目前面的列表中显示位置,如下所示:

1 lol
2 hey
3 water
4 pepsi
5 jam

3 个答案:

答案 0 :(得分:4)

假设您在from image import * File "image.py", line 98 print("Hit Enter once the image is displayed.... ", end="") ^ SyntaxError: invalid syntax

from __future__ import print_function

如果您在Python 3,请将hey = ["lol","hey","water","pepsi","jam"] for item in hey: print(hey.index(item)+1,item) 替换为Python 2声明:

print()

使用print可以获得该项目的索引。

然而,正如已经提到的,这是低效的(因为它在每次迭代时进行查找)并且如果存在重复则将不起作用。更好的方法是使用hey = ["hey","water","pepsi","jam"] for item in hey: print hey.index(item)+1,item ,因为它可以防止这两个问题。这将完成如下。

<list>.index(<item>)

enumerate

Python 3

for (i, item) in enumerate(hey, start=1):
    print(i, item)

如果您需要知道正在使用的Python版本,请在命令行中键入Python 2

答案 1 :(得分:2)

易:

hey = ["lol","hey","water","pepsi","jam"]

for (num,item) in enumerate(hey):
    print(num+1,item)

答案 2 :(得分:2)

使用start buit-in方法的enumerate参数:

>>> hey = ["lol", "hey","water","pepsi","jam"]
>>> 
>>> for i, item in enumerate(hey, start=1):
    print(i,item)


1 lol
2 hey
3 water
4 pepsi
5 jam