no classification
no tag
no datas
posted on 2023-05-03 19:30 read(322) comment(0) like(29) collect(2)
How do I access the index while iterating over a sequence with a for
loop?
xs = [8, 23, 45]
for x in xs:
print("item #{} = {}".format(index, x))
Desired output:
item #1 = 8
item #2 = 23
item #3 = 45
Use the built-in function enumerate()
:
for idx, x in enumerate(xs):
print(idx, x)
It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i]
or manually manage an additional state variable.
Check out PEP 279 for more.
Author:qs
link:http://www.pythonblackhole.com/blog/article/145/5b0b067ea9b35a8b104f/
source:python black hole net
Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!