简体   繁体   English

Python 列表索引以查找索引元素的编号(如果元素相同)

[英]Python List indexing for finding number of the indexed element if the element is the same

Im trying to find the indexed version for multiple items in a list, such as我试图找到列表中多个项目的索引版本,例如

testarray = ["l","hello","l","l"]

for x in testarray:
    if x == "l":
        print(testarray.index(x))

I want the desired output to be 1, 3, 4 , but what I'm getting is 1,1,1我希望所需的 output 为1, 3, 4 ,但我得到的是1,1,1

That's because list.index returns the index of the first occurrence of the element, to fix this, you can loop through the indices and values using enumerate :这是因为list.index返回元素第一次出现的索引,要解决这个问题,您可以使用enumerate索引和值:

testarray = ["l", "hello", "l", "l"]

for i, x in enumerate(testarray, 1):
    if x == "l":
        print(i)

Output: Output:

1
3
4

In for i, x in enumerate(testarray, 1) , i in the index, x is the value, and the second parameter 1 in enumerate tells it to start counting at 1 instead of by default at 0 .for i, x in enumerate(testarray, 1)中, i在索引中, x是值,并且enumerate中的第二个参数1告诉它从1开始计数,而不是默认从0开始计数。

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

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