gpt4 book ai didi

python - 为什么我们在 python 的 for 循环中使用 range(len)?

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:08 24 4
gpt4 key购买 nike

开始学习python,现在学习python for loop。我正在使用在线资源来学习 python。但我对 for 循环知之甚少。

输出

list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print (list[index])

list = ["geeks", "for", "geeks"]
for i in list:
print(i)

都一样那么为什么要使用range(len)方法呢?

提前致谢。

最佳答案

对于这种简单的情况,for ind in range(len(sequence)) 通常被认为是一种反模式。但是,在某些情况下使用索引很有用,例如当您需要分配回列表时:

for ind in range(len(lst)):
elem = lst[ind]
# ... Do some processing
lst[ind] = processed_elem

即使在那种情况下,range(len(...)) 也可以用 enumerate 更好地表达:

for ind, elem in enumerate(lst):
# ... Do some processing
lst[ind] = processed_elem

此外,正如在 comment 中已经指出的那样,建议避免与内置函数冲突的变量名,例如 list

关于python - 为什么我们在 python 的 for 循环中使用 range(len)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53358753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com