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 ✅
enumerate
https://docs.python.org/3/library/functions.html#enumerate
#!/usr/bin/python3
Blue = 17
GREEN = 27
RED = 22
LEDs = list([RED, GREEN, Blue])
# enumerate ✅
for index, led in enumerate(LEDs):
print('led = ', LEDs[index])
# 22, 27, 17
# 等价于,start default 0
for index, led in enumerate(LEDs, start=0):
print('led = ', LEDs[index])
# 22, 27, 17
"""
led = 22
led = 27
led = 17
"""
Python loop methods
- for
- wihle
while <expr>:
<statement(s)>
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
- ...
https://www.runoob.com/python3/python3-loop.html
demos
python
for loop
withindex
#!/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
# 等价于,start default 0
for index, led in enumerate(LEDs, start=0):
print('led = ', LEDs[index])
# 22, 27, 17
https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
REPL
https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3
PEP
Python Enhancement Proposals / Python 增强建议
PEP 8
– Style Guide for Python Code
https://peps.python.org/pep-0008/
PEP 279
– The enumerate() built-in function
https://peps.python.org/pep-0279/
refs
https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17398502.html
未经授权禁止转载,违者必究!