开发者

find position of item in for loop over a sequence [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Accessing the index in Python for loops

list = [1,2,2,3,5,5,6,7]

for item in mylist:
    ...

How can I find the index of the i开发者_JAVA技巧tem I am looking at, at some point in my loop? I can see there is a index() method for lists but it will always give me the first index of a value, so it won't work for lists with duplicate items


Have a look at enumerate

>>> for i, season in enumerate('Spring Summer Fall Winter'.split(), start=1):
        print i, season
1 Spring
2 Summer
3 Fall
4 Winter


Use an enumerator object:

for index, item in enumerate(mylist):
  ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜