如何在列表中一一输入n个数字? [英] How to input n numbers in list one by one?
问题描述
我希望我的程序询问n的值.用户输入值后, 程序接受n个值的输入,并将它们存储在列表或类似数组(在C中)中. 输入必须采用以下格式:
I want my program to ask a value of n. After user inputs the value, program takes input for n values and stores them in a list or something like array (in C). Input must be in the format:
Enter value of n: 4
2
5
7
1
我想将此输入存储在列表中以供以后使用.
I want to store this input in a list for my later use.
推荐答案
最简单的方法是这样的:
The simplest approach is something like this:
n = int(input())
l = [int(input()) for _ in range(n)]
但是这有很多问题:
- 输入无效时会崩溃.
- 它评估危险的输入-用户可以修改您的程序状态. (Python 2.x)
- 用户可以输入浮点数,程序不会抱怨,它只会默默地截断. (Python 2.x)
相反,您可以使用raw_input并将结果解析为整数.您还将需要在适当的位置进行错误处理.处理错误的方式取决于程序.
Instead you can use raw_input and parse the result as an integer. You will also need error handling in the appropriate locations. How you handle errors depend on the program.
您可能会发现此功能可能对您有所帮助:
You might find this function might be useful as a starting point:
def getNumber(prompt = ''):
while True:
try:
return int(raw_input(prompt))
except:
print "Invalid input, try again."
请注意,在Python 2.x和Python 3.x之间,input和raw_input的行为已更改. Python 3.x的输入函数的行为类似于Python 2.x的raw_input函数.
Note that the behaviour of input and raw_input has changed between Python 2.x and Python 3.x. Python 3.x's input function behaves like Python 2.x's raw_input function.
这篇关于如何在列表中一一输入n个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!