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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34753872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:28:52  来源:igfitidea点击:

How do I display the the index of a list element in Python?

pythonlistpython-3.xposition

提问by david

I have a homework assignment. I've got the following code

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

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

for item in hey:
    print(item)

Do I display the position in the list before the item, like this:

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

1 lol
2 hey
3 water
4 pepsi
5 jam

采纳答案by Leejay Schmidt

The best method to solve this problem is to enumerate the list, which will give you a tuple that contains the index and the item. Using enumerate, that would be done as follows.

解决这个问题的最好方法是枚举列表,它会给你一个包含索引和项目的元组。使用enumerate,将按如下方式完成。

In Python 3:

Python 3

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

Or in Python 2:

或在Python 2

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

If you need to know what Python version you are using, type python --versionin your command line.

如果您需要知道正在使用的 Python 版本,请python --version在命令行中输入。

回答by Baerus

Easy:

简单:

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

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

回答by Iron Fist

Use the startparameter of the enumeratebuit-in method:

使用内置方法的start参数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