英文:
Is it possible to use one input to put multiple integers into a list?
问题
marks = input("请输入分数 ")
for i in range(1, 21):
marksList = []
marksList.append(marks)
print(marksList)
英文:
marks = input("Please enter marks ")
for i in range(1,21):
marksList = []
marksList.append(marks)
print(marksList)
This is my code. I want to use the same variable and enter 20 marks using the same input, and then append it to the marks
List. Is there any way I can?
I tried researching but nothing was showing up properly.
答案1
得分: 2
你需要将input
命令放在循环内部,因为你需要重复要求用户在marks
变量中输入内容;必须将marksList
变量移出循环,以避免在每次交互中清空列表:
marksList = []
for i in range(1, 21):
marks = input("请输入成绩:")
marksList.append(marks)
print(marksList)
英文:
You need to put the input
command inside the loop, because you need to repeat the request to user to enter the content in marks
variable; it's necessary remove marksList
variable from loop to avoid to turn the list void in each interaction:
marksList = []
for i in range(1,21):
marks = input("Please enter marks ")
marksList.append(marks)
print(marksList)
答案2
得分: 1
input_string = input("输入以空格分隔的整数列表:")
int_list = [int(x) for x in input_string.split()] # 将字符串拆分为整数列表
print(int_list) # 打印整数列表
英文:
input_string = input("Enter a list of integers separated by spaces: ")
int_list = [int(x) for x in input_string.split()] # split the string into a list of integers
print(int_list) # print the list of integers
答案3
得分: 1
也许这样更合适?
n = 20
marks = []
while len(marks) < n:
isfirst = not marks
ans = input(f'请输入{n - len(marks)}{"个" if isfirst else "额外的"}分数: ')
marks += [int(i.strip()) for i in ans.split()]
print(f'谢谢。这些分数是:{marks}')
示例交互:
请输入20个分数: 1 4 2 0 10 -32 10 22
请输入12额外的分数: 1 2 5 9 2000
请输入7额外的分数: 9 8 4 1 5 2
请输入1额外的分数: 1
谢谢。这些分数是:[1, 4, 2, 0, 10, -32, 10, 22, 1, 2, 5, 9, 2000, 9, 8, 4, 1, 5, 2, 1]
英文:
Perhaps something like this would be preferable?
n = 20
marks = []
while len(marks) < n:
isfirst = not marks
ans = input(f'Please enter {n - len(marks)}{"" if isfirst else " additional"} marks: ')
marks += [int(i.strip()) for i in ans.split()]
print(f'Thanks. The marks are {marks}')
Example interaction:
Please enter 20 marks: 1 4 2 0 10 -32 10 22
Please enter 12 additional marks: 1 2 5 9 2000
Please enter 7 additional marks: 9 8 4 1 5 2
Please enter 1 additional marks: 1
Thanks. The marks are [1, 4, 2, 0, 10, -32, 10, 22, 1, 2, 5, 9, 2000, 9, 8, 4, 1, 5, 2, 1]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论