xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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

  1. for


  1. wihle
while <expr>:
    <statement(s)>
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

  1. ...

https://www.runoob.com/python3/python3-loop.html

demos

python for loop with index

#!/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


image

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-05-13 23:25  xgqfrms  阅读(24)  评论(1编辑  收藏  举报