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

时光总嘲笑我的痴心妄想 提交于 2020-05-14 14:37:38

问题


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

回答1:


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.

In Python 3:

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

Or in 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 --version in your command line.




回答2:


Use the start parameter of the enumerate buit-in method:

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



回答3:


Easy:

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

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


来源:https://stackoverflow.com/questions/34753872/how-do-i-display-the-the-index-of-a-list-element-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!