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

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 @   xgqfrms  阅读(28)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2022-05-13 SwiftUI animation All In One
2022-05-13 Xcode fold code All In One
2022-05-13 SwiftUI TabView All In One
2022-05-13 Xcode iOS project rename All In One
2021-05-13 how to delete all localStorage data in js All In One
2021-05-13 js Proxy in Action
2020-05-13 HTTP cache in depth All In One
点击右上角即可分享
微信分享提示