提问人:Child coder 提问时间:2/16/2023 最后编辑:Michael M.Child coder 更新时间:2/16/2023 访问量:63
是否可以使用一个输入将多个整数放入列表中?
Is it possible to use one input to put multiple integers into a list?
问:
marks = input("Please enter marks ")
for i in range(1,21):
marksList = []
marksList.append(marks)
print(marksList)
这是我的代码。我想使用相同的变量并使用相同的输入输入 20 个标记,然后将其附加到列表中。有什么办法可以吗?marks
我试着研究,但没有任何正确显示。
答:
2赞
amkawai
2/16/2023
#1
你需要把命令放在循环里,因为你需要重复请求用户在变量中输入内容;有必要从循环中删除变量,以避免在每次交互中使列表无效:input
marks
marksList
marksList = []
for i in range(1,21):
marks = input("Please enter marks ")
marksList.append(marks)
print(marksList)
1赞
fuwiak
2/16/2023
#2
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
1赞
Pierre D
2/16/2023
#3
也许这样的东西会更可取?
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}')
交互示例:
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]
评论
markslist = [int(x.strip()) for x in marks.split()]