Python – 短循环的语法无效

huangapple go评论67阅读模式
英文:

Python - invalid syntax for short for loop

问题

I'm having a bit of trouble with a for loop. I get SyntaxError: invalid syntax line 7 when I try to run the code below:

lst = list()
x = int(input("enter numbers, 0 to stop"))
while(x != 0):
lst.append(x)

newlst = list()
newlst.append(i) for i in lst if i not in newlst
print(newlst[1:-1])

its giving me:

newlst.append(i) for i in lst if i not in newlst
^^^
SyntaxError: invalid syntax

英文:

I'm having a bit of trouble with a for loop. I get SyntaxEror: invalid syntax line 7 when I try to run the code below:

lst = list()
x= int(input("enter numbers,0 to stop"))
while(x!=0):
    lst.append(x)

newlst = list()
newlst.append(i) for i in lst if i not in newlst
print(newlst[1:-1])

its giving me:

newlst.append(i) for i in lst if i not in newlst
                 ^^^
SyntaxError: invalid syntax

答案1

得分: 0

无法像这样迭代

for i in lst:
    if i not in newlst:
        newlst.append(i) 

或者使用列表推导式

for i in lst:
    if i not in newlst:
        newlst.append(i) 

在这种情况下,建议使用常规循环,因为列表推导式构建一个无用的包含None值的列表并将其丢弃。

英文:

No way to iterate like this

newlst.append(i) for i in lst if i not in newlst

You can do it by regular loop:

for i in lst:
    if i not in newlst:
        newlst.append(i) 

or by a list comprehension

[newlst.append(i) for i in lst if i not in newlst]

In this case the regular loop is recommended because a list comprehension builds a useless list of None values and throws it away.

huangapple
  • 本文由 发表于 2023年5月17日 23:47:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定