在python中通过if条件追加列表

son*_*089 1 python for-loop list append python-3.x

这可能是一个非常基本的问题,但我意识到我不明白一些事情。

在 for 循环中追加新内容时,如何提出条件并仍然追加该项目?

例如:

alist = [0,1,2,3,4,5]
new = []
for n in alist:
    if n == 5:
        continue
    else:
        new.append(n+1)

print(new) 
Run Code Online (Sandbox Code Playgroud)

让我明白

[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

如何得到

[1, 2, 3, 4, 5, 5] # 4 is incremented, 5 is added 'as is'
Run Code Online (Sandbox Code Playgroud)

本质上,我想告诉 python 不要经历n+1when n==5

这是唯一的解决方案吗?将 n==5 单独附加到列表中,然后将新的和单独的列表相加?

Cyp*_*ius 7

为什么不直接附加 the5而不是 using continue,还有其他条件吗?

for n in alist:
    if n == 5:
        new.append(n)
    else:
        new.append(n+1)
Run Code Online (Sandbox Code Playgroud)