简体   繁体   English

如何在python中使用for循环从用户那里获取多个输入?

[英]how to take multiple inputs from user using for loop in python?

I am making a basic program in which I want to store multiple inputs from the user in the predefined list.我正在制作一个基本程序,我想在预定义列表中存储来自用户的多个输入。 My approach我的方法

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

But I don't want to use input function multiple times.但我不想多次使用输入功能。 Desired Output:期望的输出:

exampleList = [2,3,5,4,1]

You could store all of these inputs in a list called inputs using the following:您可以使用以下命令将所有这些输入存储在一个名为inputs的列表中:

inputs = list()                                                         

for idx in range(1, 5): 
    inputs.append(input(f"Enter the choice of user {idx}: ")) 

Test time using ipython :使用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']

You can also try using list Comprehension ,it is most elegant way to define and create a list.您也可以尝试使用 list Comprehension ,这是定义和创建列表的最优雅的方式。

>>>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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM