简体   繁体   中英

Index of element in an array in Python

I'm trying to display indices of an array in a for loop in Pyrhon.

Here is my code:

computerPlayersList = [nbr]
For computerPlayer in computerPlayersList:
     print(computerPlayersList.index(computerPlayer))

But this is not working ? What's the correct displaying method please ? Thank you

In python, keywords must be written in lowercase. Use for , not For :

computerPlayersList = [5, 3, 9, 6]
for computerPlayer in computerPlayersList:
     print(computerPlayersList.index(computerPlayer))

returns

0
1
2
3

You can use the enumerate() method for index and the value in the following manner:

for index,computerPlayer in enumerate(computerPlayersList):
   print (index,computerPlayer)

Code :

computerPlayersList = [10,20,30]
for counter,computerPlayer in enumerate(computerPlayersList):
     print(counter,computerPlayer)

using enumerate is also a great option. the counter variable will be having the index value of each item.

Output :

0 10
1 20
2 30

Firstly "For" lower case since it's a keyword.

    computerPlayersList = ["nbr","abc"]
    for computerPlayer in computerPlayersList:
          print(computerPlayersList.index(computerPlayer))

or

     computerPlayersList = [10,20,30]
    for computerPlayer in computerPlayersList:
          print(computerPlayersList.index(computerPlayer))

The elements in the list are either string or integer/float so list cannot have variable names.

    >>> a=10
    >>> b=[]
    >>> c=b[a]
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IndexError: list index out of range

I'm guessing that you are giving variable names inside the list.

So there are two errors, next time post that error message so that we can see what exactly is the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM