简体   繁体   English

如何使输入接受空格?

[英]How to make an input accept spaces?

I need a program in Python , which would ask a user to enter multiple numbers into one line, each number separated by a space. 我需要使用Python编写的程序,该程序将要求用户在一行中输入多个数字,每个数字之间用空格分隔。 Like Enter your numbers: 2 1 5 8 9 5 and I need for it to print out [2, 1, 5, 8, 9, 5] 例如Enter your numbers: 2 1 5 8 9 5 ,我需要打印出来[2, 1, 5, 8, 9, 5]

But the program I made so far does not accept spaces, how do I change that? 但是到目前为止,我编写的程序不接受空格,该如何更改呢? Also is there a way to make the number go in order like from smallest to biggest? 还有没有办法使数字按从小到大的顺序排列?

Here's what I have so far: 这是我到目前为止的内容:

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)

只需按空格分开,使用列表推导检查字符串是否由数字组成:

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

Use a try/except and sorted: 使用try / except进行排序:

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

If a user can enter negative numbers then isdigit is going to fail. 如果用户可以输入负数,则isdigit将失败。

Also if a user enters 1 2 3 f 5 I think it should be considered a mistake not ignored. 同样,如果用户输入1 2 3 f 5我认为应该将其视为不可忽略的错误。

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

This generates a list of strings which contain the numbers ( s.split(' ') ), which are in turn converted to ints by the map. 这将生成一个字符串列表,其中包含数字( s.split(' ') ),这些数字又会被映射转换为int。

Finally, to sort the list, use sort(s) . 最后,要对列表进行排序,请使用sort(s)

Edit: as stated in the official doc , using split(sep=' ') would throw an exception if some numbers were separated by two spaces, because in that case an empty string would be generated by the split ( '1 2'.split(' ') == ['1', '', '2'] ), and the int() would fail to convert it. 编辑:如官方文档中所述,如果某些数字用两个空格分隔,则使用split(sep=' ')会引发异常,因为在这种情况下,拆分会生成一个空字符串( '1 2'.split(' ') == ['1', '', '2'] ),而int()将无法对其进行转换。

Thanks to Padraic Cunningham for pointing this out! 感谢Padraic Cunningham指出了这一点!

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

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