英文:
On counters in for loops in Python
问题
list = ['a', 'b', 'c', 'd']
# 第一个选项
k = 0
for thing in list:
print(thing)
k = k + 1
# 第二个选项
for thing in list:
print(thing)
这两个选项输出相同的结果。有没有更喜欢其中一个的原因?
此外,当第一个选项中的 k 值变成 4 时会发生什么?在 Python 中是否硬编码了当使用完长度为 n 的列表的所有元素后,算法会在第 n 步强制停止(即当计数器达到 k=n 时)?
英文:
list = ['a', 'b', 'c', 'd']
#first option
k=0
for thing in list:
print(thing)
k=k+1
#second option
for thing in list:
print(thing)
The two options below output the same result. Is there a reason to prefer one over the other?
Also, what happens when the value of k becomes 4 in the first option? Is it just somehow hard-coded in Python that when all the elements of a list of length n have been "used up", then the algorithm is forced to stop at step n (i.e., when the counter becomes k=n)?
答案1
得分: 2
for
通过内部计数器遍历列表。 (实际上,for
循环调用列表的 __iter__()
方法,由该方法返回的 listiterator
维护计数器,但这是细节。) 它从0开始计数,并在每次循环通过时递增,直到达到末尾。
如果你需要索引以满足自己的需求,你可以像你的第一个选项那样自行维护它,或者更好的办法是使用 enumerate()
:
for k, thing in enumerate(list):
# 等等
你也可以使用 range
来遍历索引并从中获取列表项。 一般来说,这不是最佳方法,但我为了完整性而展示它:
for k in range(len(list)):
thing = list[k]
# 等等
英文:
for
iterates over a list using an internal counter. (Actually the for
loop calls the list's __iter__()
method and it's the listiterator
returned by that method that maintains the counter, but that's a detail.) It starts the counter at 0 and increments it on each pass through the loop, until it reaches the end.
If you need the index for your own purposes, you can maintain it yourself as in your first option, or, better, you can use enumerate()
:
for k, thing in enumerate(list):
# etc
You could also use range
to iterate over the indexes and get the list item from that. In general this isn't the best way to do it, but I'm showing it for completeness.
for k in range(len(list)):
thing = list[k]
# etc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论