Python for loop with index All In One
带索引的 Python for 循环
error ❌
#!/usr/bin/python3
Blue = 17
GREEN = 27
RED = 22
LEDs = list([RED, GREEN, Blue])
for led,i in LEDs:
print('led = ', LEDs[i])
# 22, 27, 17
"""
Traceback (most recent call last):
File "script.py", line 9, in
for led,i in LEDs:
TypeError: cannot unpack non-iterable int object
Exited with error status 1
"""
solution ✅
#!/usr/bin/python3
Blue = 17
GREEN = 27
RED = 22
LEDs = list([RED, GREEN, Blue])
for index, led in enumerate(LEDs):
print('led = ', LEDs[index])
# 22, 27, 17
"""
led = 22
led = 27
led = 17
"""