如何获得一系列数字,不知道有多少是在python中

时间:2013-10-29 08:59:10

标签: python

我想获得一系列数字,但我不知道用户想要输入多少个数字....我不希望有这样的数字:

print("please enter a number or -1 to exit")
while(int(input())!=-1):

或类似的东西:

print("how many numbers do you want to enter ? ")
howmany=int(input())
for i in range(howmay):

除了这些之外还有什么方法吗?

4 个答案:

答案 0 :(得分:1)

在用户给出空行之前询问如何:

line = raw_input()
while(line):
    # process line
    line=raw_input()

或者更优雅(来自@ Bakuriu的评论):

for line in iter(raw_input, ''):
    # process line

在python 3.x中使用input而不是raw_input

答案 1 :(得分:1)

One-line-solution(适用于Python 2.7 +):

list(iter(lambda: input('Enter number (or -1 to finish): '), -1))

使用它:

>>> numbers = list(iter(lambda: input('Enter number (or -1 to finish): '), -1))
Enter number (or -1 to finish): 1
Enter number (or -1 to finish): 2
Enter number (or -1 to finish): 3
Enter number (or -1 to finish): 4
Enter number (or -1 to finish): -1
>>> numbers
[1, 2, 3, 4]

注意:在Python 2.7+中使用input()可能不安全,因为它会对用户输入执行eval()。为了更安全的方法:

Python 2.7 +

list(iter(lambda: int(raw_input('Enter number (or -1 to finish): ')), -1))

Python 3。+

list(iter(lambda: int(input('Enter number (or -1 to finish): ')), -1))

答案 2 :(得分:1)

一些替代方案(对于python 3 。在python2中用input替换raw_input):

在一行中使用逗号分隔的数字列表:

import ast
numbers = ast.literal_eval(input('Enter comma-separated sequence of numbers'))
# or numbers = [int(el) for el in input('Enter ...').split(',')]

在一行中使用以空格分隔的数字序列:

numbers = [int(el) for el in input('Enter ...').split()]

使用空输入作为哨兵,每行一个数字:

numbers = [int(el) for el in iter(input, '')]

使用非空输入标记,每行一个数字:

numbers = [int(el) for el in iter(input, 'END')]  #ends when user enters END.

询问元素数量

numbers = [int(input()) for _ in range(input('Number of elements'))]

从文件输入(使用shell重定向)/使用 Ctrl + D 作为结束标记,每行一个数字:

import sys
text = sys.stdin.read()
numbers = [int(el) for el in text.splitlines()]

如果您将splitlines()替换为split(),则用户可以将这些数字放在同一行或多行。

答案 3 :(得分:0)

假设用户仅提供int s:

howMany = int(raw_input("How many numbers would you like to add?: "))
numbers = []
for i in range(1,howMany+1):
  numbers.append(int(raw_input("Please enter the %d-th number: " %i)))

可替换地:

numbers = [int(i) for i in raw_input("Please enter all your numbers, separated by spaces: ").split()]