python-2.7 - 如何读取一串数字并通过输入-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]
但是,当然,代码不起作用。
解决方案
您可以使用函数 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中受保护的变量名
推荐阅读
- php - Codeigniter 3 升级会话锁定导致问题
- elasticsearch - Kubernetes 集群上的 Elasticsearch 集群。进还是出?
- powershell - 比较对象不返回任何东西
- sas - 使用 COALESCE 函数合并 SAS 行
- ios - Pod 无法安装或更新
- windows - Windows 中的 CALL 不会等待批处理完成
- robocopy - powershell 的 Copy-Item 命令不适用于大文件
- windows - 从浏览器启动 i2 分析师笔记本
- python - 从 CSV 输入 Python 中查找最后一行
- javascript - 如果文件不存在,则无法使用 selenium (js) 将密钥发送到文件表单字段