用户输入整数列表

时间:2015-04-13 21:17:40

标签: python string list python-3.x int

我正在尝试创建一段代码,允许我一次要求用户输入5个数字,这些数字将存储到列表中。例如,代码将被运行,类似的东西将出现在shell

Please enter five numbers separated by a single space only:

用户可以像这样回复

 1 2 3 4 5 

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

5 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

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

答案 1 :(得分:1)

这样做的最佳方式可能是列表理解。

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

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

答案 2 :(得分:0)

使用raw_input()函数可以非常轻松地实现这一点,然后使用split()map()

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:-1)

这是将用户输入带入列表的一种微妙方式:

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

print(l)

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

相关问题