英文:
"[" is not closed ? when I've already closed it
问题
I could input multiple times into a list up to a point using while.
However, I cannot use list comprehension because it said the "[" is not closed.
what works
x = int(input('enter the number of numbers you want to enter '))
ans = []
while len(ans) < x:
i = int(input('enter the number '))
ans.append(i)
print(ans)
what I want to simplify but produce error: ""[" is not closed "
x = input('enter the number of numbers you want to enter')
ans = [i for i in input() while len(ans) < x]
#Update2. This works now. I think because list comprehension does not mean it could assign value with equality signs.
x = int(input('enter the number of numbers you want to enter'))
ans = [input() for i in range(int(x))]
英文:
I could input multiple times into a list up to a point using while.
However, I cannot use list comprehension because it said the "[" is not closed.
what works
x = int(input('enter the number of numbers you want to enter '))
ans = []
while len(ans) < x:
i = int(input('enter the number '))
ans.append(i)
print(ans)
what I want to simplify but produce error: ""[" is not closed "
x = input('enter the number of numbers you want to enter')
ans = [i = input() while len(ans) < x]
#Update2. This works now. I think because list comprehension does not mean it could assign value with equality signs.
x = int(input('enter the number of numbers you want to enter'))
ans = [input() for i in range(int(x))]
答案1
得分: 2
欢迎!
看起来您试图使用list comprehension简化您的while循环。然而,由于两个原因,这种简化会导致语法错误:
- 您不能在列表理解中使用等号进行变量赋值 - 此外,在这里赋值没有任何原因
- 列表理解不能与
while
循环一起使用。相反,您可以改用for循环
修复上述两个问题,一个可行的解决方案可能是:
x = int(input('输入要输入的数字数量:'))
ans = [int(input('输入数字:')) for _ in range(x)]
print(ans)
请注意,_
只是一个空白占位符变量,因为它没有用于任何操作。
英文:
Welcome!
It seems you are trying to simplify your while loop using a list comprehension. However, this simplification produces a syntax error due to two things
- You cannot assign variables inside list comprehensions with an equality sign - additionally there is no reason to assign here anyway
- List comprehensions does not work with
while
loops. Instead you can change to using a for loop
Fixing the above two issues, a working solution could be:
x = int(input('enter the number of numbers you want to enter '))
ans = [int(input('enter the number ')) for _ in range(x)]
print(ans)
Note that the _
is just a blank placeholder variable as it is not used for anything
答案2
得分: 0
尝试这个:
x = input('输入您想要输入的数字数量')
ans = [int(input()) for i in range(int(x))]
print(ans)
英文:
Try this:
x = input('enter the number of numbers you want to enter')
ans = [int(input()) for i in range(int(x))]
print(ans)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论