2024-10-06 16:19:58 发布
网友
我想从python3的单行输入中读取一个整数数组。 例如:将此数组读取到变量/列表
1 3 5 7 9
arr = input.split(' ')但这不会将它们转换为整数。它创建字符串数组
arr = input.split(' ')
for i,val in enumerate(arr): arr[i] = int(val)
第二个是为我工作。但我正在寻找一个优雅的(单线)解决方案。
你可以从下面的程序中得到很好的参考
# The following command can take n number of inputs n,k=map(int, input().split(' ')) a=list(map(int,input().split(' '))) count=0 for each in a: if each >= a[k-1] and each !=0: count+=1 print(count)
使用map:
map
arr = list(map(int, input().split()))
只需添加,在Python 2.x中不需要调用list(),因为map()已经返回了list,但在Python 3.x"many processes that iterate over iterables return iterators themselves"。
list()
map()
list
此输入必须添加()即括号对,以遇到错误。这对3.x和2.x Python都有效
编辑:在使用Python将近4年之后,才偶然发现这个答案,并意识到接受的答案是一个更好的解决方案。
使用list comprehensions: 下面是关于ideone的示例:
arr = [int(i) for i in input().split()]
如果您使用的是Python 2,那么应该使用raw_input()。
raw_input()
你可以从下面的程序中得到很好的参考
使用
map
:只需添加,在Python 2.x中不需要调用
list()
,因为map()
已经返回了list
,但在Python 3.x"many processes that iterate over iterables return iterators themselves"。此输入必须添加()即括号对,以遇到错误。这对3.x和2.x Python都有效
编辑:在使用Python将近4年之后,才偶然发现这个答案,并意识到接受的答案是一个更好的解决方案。
使用list comprehensions:
下面是关于ideone的示例:
arr = [int(i) for i in input().split()]
如果您使用的是Python 2,那么应该使用
raw_input()
。相关问题 更多 >
编程相关推荐