可以使用一个输入将多个整数放入一个列表吗?

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

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) &lt; n:
    isfirst = not marks
    ans = input(f&#39;Please enter {n - len(marks)}{&quot;&quot; if isfirst else &quot; additional&quot;} marks: &#39;)
    marks += [int(i.strip()) for i in ans.split()]

print(f&#39;Thanks. The marks are {marks}&#39;)

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]

huangapple
  • 本文由 发表于 2023年2月16日 07:58:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466541.html
匿名

发表评论

匿名网友

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

确定