Python for loop with index All In One
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
"""
demos
REPL
https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3
refs
https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops
https://docs.python.org/3/library/functions.html#enumerate
https://peps.python.org/pep-0279/
©xgqfrms 2012-2021
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
未经授权禁止转载,违者必究!