gpt4 book ai didi

python - 为什么 i += 1 更改为 i += 2 有效?

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:08 25 4
gpt4 key购买 nike

第一次在这里提问

我尝试让高度超过 200 厘米的玩家加入,但我不知道为什么它不起作用,直到我将 i += 1 调整为 i += 2,我仍然不知道它为什么有效。

顺便说一下,我尝试使用 while 循环而不是 for 循环来编写这段代码。

提前致谢!

players = [['James', 202],
['Curry', 193],
['Durant', 205],
['Jordan', 199],
['David', 211]]

i = 0
while i < len(players):
if players[i][1] < 200:
continue
print(players[i])
i += 1

最佳答案

for 循环重构并仅在你想做某事时指定:

players = [['James', 202], ['Curry', 193], ['Durant', 205],
['Jordan', 199], ['David', 211]]

for p, height in players:
if height >= 200:
print(p)

# James
# Durant
# David

或者使用列表理解:

[p for p, height in players if score >= 200]
# ['James', 'Durant', 'David']

您的代码的问题在于,当它点击 continue 时,i 不会随着循环的下一次迭代开始而递增。 Read up on continue here .以下是使用 while 循环执行此操作的方法:

i = 0
while i < len(players):
p, height = players[i]
if height >= 200:
print(p)
i += 1

# James
# Durant
# David

关于python - 为什么 i += 1 更改为 i += 2 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48609632/

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