Python 2.7 如何读取数字序列并通过输入-1停止数据输入?
开发代码以读取用户输入的数字序列并显示。用户被告知输入数字-1以指示数据输入的结束Python 2.7 如何读取数字序列并通过输入-1停止数据输入?,python-2.7,Python 2.7,开发代码以读取用户输入的数字序列并显示。用户被告知输入数字-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
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)
旁注:小心列表是python中受保护的变量名Holy moly!非常感谢你!
# 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']