Skip to main content
 首页 » 编程设计

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

2025年05月04日15lovecherry

第一次在这里提问

我尝试让高度超过 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