开发者

How to output an index while iterating over an array in python [duplicate]

开发者 https://www.devze.com 2023-01-02 17:08 出处:网络
This question alr开发者_JAVA百科eady has answers here: Accessing the index in 'for' loops
This question alr开发者_JAVA百科eady has answers here: Accessing the index in 'for' loops (26 answers) Closed 8 years ago.

I am iterating over an array in python:

for g in [ games[0:4] ]:
    g.output()

Can I also initialise and increment an index in that for loop and pass it to g.output()?

such that g.output(2) results in:

Game 2 - ... stuff relating to the object `g` here.


Like this:

for index, g in enumerate(games[0:4]):
    g.output(index)


Use the built-in enumerate method:

for i,a in enumerate(['cat', 'dog']):
   print '%s is %d' % (a, i)

# output:
# cat is 0
# dog is 1
0

精彩评论

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