0

我想得到一系列数字,但我不知道用户要输入多少个数字......而且我不想有这样的东西:

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

4 回答 4

1

单行解决方案(对于 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))
于 2013-10-29T09:07:00.700 回答
1

How about asking until user gives empty line:

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

Or one more elegantly (from @Bakuriu's comment):

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

In python 3.x use input instead of raw_input.

于 2013-10-29T09:02:44.107 回答
1

一些替代方案(对于 python 3。在 python2 中替换inputraw_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()则用户可以将数字放在同一行或多行上。

于 2013-10-29T09:07:54.693 回答
0

假设用户只给你ints:

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()]
于 2013-10-29T09:05:23.387 回答