我正在制作一个基本程序,我想在其中将用户的多个输入存储在预定义列表中。 我的方法
exampleList = []
exampleList = input("Enter the choice of user1: ")
exampleList = input("Enter the choice of user2: ")
exampleList = input("Enter the choice of user3: ")
exampleList = input("Enter the choice of user4: ")
exampleList = input("Enter the choice of user5: ")
# I want to store 5 number inputs in examples list
但是我不想多次使用输入功能。 所需的输出:
exampleList = [2,3,5,4,1]
答案 0 :(得分:3)
您可以使用以下命令将所有这些输入存储在名为inputs
的列表中:
inputs = list()
for idx in range(1, 5):
inputs.append(input(f"Enter the choice of user {idx}: "))
使用ipython
测试时间:
In [0]: inputs = list()
...: for idx in range(1, 6):
...: inputs.append(input(f"Enter the choice of user {idx}: "))
Enter the choice of user 1: 12
Enter the choice of user 2: 1234
Enter the choice of user 3: 54326
Enter the choice of user 4: 3232
Enter the choice of user 5: 55
In [1]: print(inputs)
['12', '1234', '54326', '3232', '55']
答案 1 :(得分:0)
您还可以尝试使用列表理解,这是定义和创建列表的最简便方法。
>>>a=[input("enter choice of user%d : "%(i+1)) for i in range(5)]
enter choice of user1 : 2
enter choice of user2 : 3
enter choice of user3 : 4
enter choice of user4 : 5
enter choice of user5 : 1
>>>print(a)
[2,3,4,5,1]