首页 > 解决方案 > 如何读取一串数字并通过输入-1停止数据输入?

问题描述

开发代码以读取用户输入的数字序列并显示它。用户被告知输入数字 -1 表示数据输入结束。

 input_list = raw_input('Enter sequence of numbers and enter -1 to indicate the end of data entry: ')

 list = input_list.split()
 list = [int(a) for a in input_list:if(a == -1): break]

 print 'list: ',list

我期望得到:

ex1)输入数字序列,输入-1表示数据输入结束:1 3 5 -1 6 2

列表:[1,3,5]

ex2)输入数字序列,输入-1表示数据输入结束:1 3 5 2 4 -1 2 6 2

列表:[1、3、5、2、4]

但是,当然,代码不起作用。

标签: python-2.7

解决方案


您可以使用函数 split 两次。第一个拆分将允许您停在第一个“-1”,第二个拆分将允许您区分数字:

input_list = raw_input('Enter sequence of numbers and enter -1 to indicate the end of data entry: ')

numbers = input_list.split('-1')[0].split(' ')[:-1]
print(numbers)

# With  : 1 3 5 -1 6 2
Out [1] : ['1', '3', '5']
# With 1 3 5 2 4 -1 2 6 2
Out [2] : ['1', '3', '5', '2', '4']

旁注:小心列表是python中受保护的变量名


推荐阅读