用户输入整数列表

User input integer list

我正在尝试创建一段代码,让我可以要求用户一次输入 5 个数字,这些数字将被存储到一个列表中。例如,代码将是 运行 并且类似这样的内容将出现在 shell

Please enter five numbers separated by a single space only:

用户可以这样回复

 1 2 3 4 5 

然后数字 1 2 3 4 5 将作为整数值存储到列表中,稍后可以在程序中调用。

你可以使用这样的东西:

my_list = input("Please enter five numbers separated by a single space only")
my_list = my_list.split(' ')

执行此操作的最佳方法可能是列表理解。

user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]

这将在空格处拆分用户的输入,并创建一个整数列表。

这可以通过使用 raw_input() 函数很容易地实现,然后使用 split()map()

将它们转换为字符串列表
num = map(int,raw_input("enter five numbers separated by a single space only" ).split())
[1, 2, 3, 4, 5]

您需要使用正则表达式,因为用户也可能输入非整数值:

nums = [int(a) for a in re.findall(r'\d+', raw_input('Enter five integers: '))]
nums = nums if len(nums) <= 5 else nums[:5] # cut off the numbers to hold five

这是将用户输入放入列表的巧妙方法:

l=list()
while len(l) < 5: # any range
    test=input()
    i=int(test)
    l.append(i)

print(l)

应该很容易理解。任何范围范围都可以应用于 while 循环,并且只需请求一个数字,一次一个。