简体   繁体   中英

Show index of each string in a list

I wish to find the index of each integer(I converted it to string since I do not know any alternate ways) in a list.

Example, I have a list:

a = [0,3,3,7,5,3,11,1] # My list
a = list(map(str, a)) # I map it to string for each integer in the list, is there any better way than this? I would like to learn

for x in a: # I then loop each str in the list
    print(a.index(x)) # here I print each index of the str

My output is:

0
1
1
3
4
1
6
7

My expected output should be:

0
1
2
3
4
5
6
7

I think you're looking for enumerate()

a = ['apple', 'ball', 'cat']

for i, it in enumerate(a):
    print(i)

>>> output
0
1
2

.index() is not used for showing its original index but the first index that matches the value you passed into.

You can use enumerate to get both the index and the value in the list.

a = [0,3,3,7,5,3,11,1]
for index, value in a:
    print('{} {}'.format(index, value))

And not sure why you wanted to convert a to a list of strings instead of integers?

You can use Python's built-in function enumerate() .

In your case you can do:

a = [0,3,3,7,5,3,11,1] 

for index, element in enumerate(a):
    print index

The output should be:

0
1
2
3
4
5
6
7

You can check the documentation in this link .

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