简体   繁体   中英

How do I enumerate the following list?

I am trying to enumerate the following list but the output I get is not correct:

colours = ["red", "green", "blue", "yellow"]
for p, colours in enumerate(colours): 
    print(p, ("-->"), colours[p])

The output I get is:

0 --> r
1 --> r
2 --> u
3 --> l

which is not what I am after of course, any help? Thanks!

colours = ["red", "green", "blue", "yellow"]
for p, colour in enumerate(colours): 
    print (f"{p} --> {colour}")

1st: don't use same name for element of a loop as a variable you are iterating. 2nd: what output are you expecting? Single line when printing? This would be done in my update. It puts variables in f-string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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