如何在python中从用户读取数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27925058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to read array elements from user in python
提问by Tarun Kumar
I am trying to read array elements as
我正在尝试将数组元素读取为
4 #no. of elements to be read in array
1 2 3 4
what i have tried by referring other answers
我通过参考其他答案所尝试的
def main():
n=int(input("how many number you want to enter:"))
l=[]
for i in range(n):
l.append(int(input()))
this works fine if i give input as
如果我将输入作为
4 #no. of elements to be read
1
2
3
4
but if i try to give like
但如果我尝试给予喜欢
4 #no. of element to be read
1 2 3 4
I get error as:
我得到错误为:
ValueError: invalid literal for int() with base 10: '1 2 3 4'
Please help me with this
请在这件事上给予我帮助
回答by Maroun
回答by Reut Sharabani
Your first approach is OK, for the second way use this:
你的第一种方法没问题,第二种方法使用这个:
n=int(input("how many number you want to enter:"))
l=map(int, input().split())[:n] # l is now a list of at most n integers
This will map
the function int
on the split parts (what split
gives) of the user input (which are 1
, 2
, 3
and 4
in your example.
这将map
在功能int
上分裂部(什么split
用户输入的给出)(这是1
,2
,3
和4
在你的榜样。
It also uses slicing (the [:n]
after map
) to slice in case the user put more integers in.
它还使用切片([:n]
after map
)来切片,以防用户放入更多整数。
回答by Ganesh Kamath - 'Code Frenzy'
n = input("how many number you want to enter :")
l=readerinput.split(" ")
回答by Loupi
The input()
function returns a string that the user enters. The int()
function expects to convert a number as a string to the corresponding number value. So int('3')
will return 3. But when you type in a string like 1 2 3 4
the function int()
does not know how to convert that.
该input()
函数返回用户输入的字符串。该int()
函数期望将数字作为字符串转换为相应的数字值。所以int('3')
会返回 3。但是当你输入一个字符串时1 2 3 4
,函数int()
不知道如何转换它。
You can either follow your first example:
你可以按照你的第一个例子:
n = int(input('How many do you want to read?'))
alist = []
for i in range(n):
x = int(input('-->'))
alist.append(x)
The above requires you to only enter a number at a time.
以上要求您一次只能输入一个数字。
Another way of doing it is just to split the string.
另一种方法是拆分字符串。
x = input('Enter a bunch of numbers separated by a space:')
alist = [int(i) for i in x.split()]
The split()
method returns a list of numbers as strings excluding the spaces
该split()
方法将数字列表作为字符串返回,不包括空格