英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论