[英]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.