繁体   English   中英

显示列表中每个字符串的索引

[英]Show index of each string in 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

我的输出是:

0
1
1
3
4
1
6
7

我的预期输出应为:

0
1
2
3
4
5
6
7

我认为您正在寻找enumerate()

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

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

>>> output
0
1
2

.index()并不用于显示其原始索引,而是用于显示与您传递的值匹配的第一个索引。

您可以使用enumerate来获取索引和列表中的值。

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

不确定为什么要将a转换为字符串列表而不是整数?

您可以使用Python的内置函数enumerate()

在您的情况下,您可以执行以下操作:

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

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

输出应为:

0
1
2
3
4
5
6
7

您可以在此链接中查看文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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