如何使输入接受空格?

问题描述:

我需要一个程序在Python,它会要求用户在一行中输入多个数字,每个数字用空格分隔。像Enter your numbers: 2 1 5 8 9 5和我需要它打印[2, 1, 5, 8, 9, 5]如何使输入接受空格?

但我到目前为止的程序不接受空格,我该如何改变?还有一种方法可以让数字按从小到大的顺序排列?

这是我到目前为止有:

elx = [] 

el = input("Enter your numbers: ") 
for i in el: 
    if el.isdigit(): 
     elx.append(el) 
     break 
    if not el.isdigit(): 
     print ("Number is invalid") 
     continue 

print (elx) 
+0

我的答案是Python,所以不需要大胆。 – 2015-03-30 19:27:10

+0

在你的例子中,'el'不是数字列表,而是字符串''2 1 5 8 9 5''。所以你可以用空格分割这个字符串'el.split('')' – 2015-03-30 19:27:24

由空格就拆,使用列表理解来检查字符串由数字组成:

nums = sorted([int(i) for i in input().split() if i.isdigit()]) 

使用try/except和排序:

while True: 
    el = input("Enter your numbers: ") 
    try: 
     elx = sorted(map(int, el.split())) 
     break 
    except ValueError: 
     print("Invalid input") 

如果用户可以输入负数,那么isdigit将会失败。

此外,如果用户输入1 2 3 f 5我认为这应该被视为一个不被忽视的错误。

+0

你为什么要排序?该列表与字符串的顺序相同。 – 2015-03-30 19:29:51

+0

@MalikBrahimi,你看过这个问题吗? *还有一种方法可以使数字从最小到最大排列* – 2015-03-30 19:30:22

+1

我的不好,修复了我的答案。感谢您的提醒。 – 2015-03-30 19:32:47

s = input('Gimme numbers! ') # '1 2 3' 
s = list(map(int, s.split())) 
print(s) # [1, 2, 3] 

这产生含有数字(s.split(' ')),其依次由地图转换为整数的字符串列表。

最后,要对列表进行排序,请使用sort(s)

编辑:作为official doc指出,使用split(sep=' ')将抛出一个异常,如果一些数据被两个空格分开的,因为在这种情况下,一个空字符串会被拆分('1 2'.split(' ') == ['1', '', '2'])中产生,而int()将无法转换它。

感谢Padraic Cunningham指出这一点!

+1

try's = list(map(int,“1 2”.split('')))',你不应该传递任何东西来分割。 – 2015-03-30 19:32:45

+1

你说得对,如果一些数字被两个空格分隔,传递'sep'参数会抛出异常。我会编辑我的答案。谢谢! – maahl 2015-03-30 19:41:02