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

This question already has an answer here:

  • Accessing the index in 'for' loops? 17 answers

  • Assuming that you are in Python 3 :

    hey = ["lol","hey","water","pepsi","jam"]
    
    for item in hey:
        print(hey.index(item)+1,item)
    

    If you are in Python 2 , replace the print() with just the print statement:

    hey = ["hey","water","pepsi","jam"]
    
    for item in hey:
        print hey.index(item)+1,item
    

    Using <list>.index(<item>) will get you the index of that item.

    However, as has been mentioned, this is inefficient (as it does a lookup each iteration) and will not work if there are duplicates. The better method is to use enumerate , as it prevents both of these issues. 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.


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

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

    简单:

    hey = ["lol","hey","water","pepsi","jam"]
    
    for (num,item) in enumerate(hey):
        print(num+1,item)
    
    链接地址: http://www.djcxy.com/p/24020.html

    上一篇: 如何在Python中返回列表的索引

    下一篇: 如何在Python中显示列表元素的索引?