为什么我们在 python 的 for 循环中使用 range(len)? [英] Why we use range(len) in for loop in python?

查看:86
本文介绍了为什么我们在 python 的 for 循环中使用 range(len)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习python,现在正在学习python for loop.我正在使用在线资源来学习 python.但我对 for 循环有点困惑.

I have started learning python and now learning python for loop. I am using online source to learn python. But i am little but confused about for loop.

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) 方法呢?

are same then why to use range(len) method?

提前致谢.

推荐答案

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

For such simple case, for ind in range(len(sequence)) is generally considered an anti-pattern. The are cases when it's useful to have the index around, though, such as when you need to assign back to the list:

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

即使在这种情况下,range(len(...))enumerate:

Even in that case, range(len(...)) is better expressed with enumerate:

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

此外,正如在 comment,建议避免与内置变量名冲突的变量名,例如list.

Also, as already pointed out in a comment, it's recommended to avoid variable names that clash with built-ins, such as list.

这篇关于为什么我们在 python 的 for 循环中使用 range(len)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆