如何从python3中的单行输入读取整数数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18332801/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:30:06  来源:igfitidea点击:

How to read an array of integers from single line of input in python3

pythonarrayslistinputpython-3.2

提问by sachinjain024

I want to read an array of integers from single line of input in python3. For example: Read this array to a variable/list

我想从python3的单行输入中读取一个整数数组。例如:将此数组读入变量/列表

1 3 5 7 9

What I have tried

我试过的

  1. arr = input.split(' ')But this does not convert them to integers. It creates array of strings

  2. arr = input.split(' ')

    for i,val in enumerate(arr): arr[i] = int(val)

  1. arr = input.split(' ')但这不会将它们转换为整数。它创建字符串数组

  2. arr = input.split(' ')

    for i,val in enumerate(arr): arr[i] = int(val)

2nd one is working for me. But I am looking for an elegant(Single line) solution.

第二个正在为我工​​作。但我正在寻找一个优雅的(单行)解决方案。

采纳答案by Saullo G. P. Castro

Use map:

使用map

arr = list(map(int, input().split()))

Just adding, in Python 2.x you don't need the to call list(), since map()already returns a list, but in Python 3.x "many processes that iterate over iterables return iterators themselves".

只是补充一点,在 Python 2.x 中,您不需要调用list(),因为map()已经返回了list,但在 Python 3.x 中“许多迭代可迭代对象的进程本身返回迭代器”

This input must be added with () i.e. parenthesis pairs to encounter the error. This works for both 3.x and 2.x Python

这个输入必须加上 () 即括号对才能遇到错误。这适用于 3.x 和 2.x Python

回答by harmands

Edit: After using Python for almost 4 years, just stumbled back on this answer and realized that the accepted answer is a much better solution.

编辑:在使用 Python 近 4 年后,偶然发现了这个答案,并意识到接受的答案是一个更好的解决方案。

Same can be achieved using list comprehensions:
Here is example on ideone:

使用列表推导也可以实现相同的目的:
这是ideone 的示例:

arr = [int(i) for i in input().split()]

arr = [int(i) for i in input().split()]

If you are using Python 2, you should use raw_input()instead.

如果您使用的是 Python 2,则应raw_input()改用。

回答by Vamsi kalyan

You can get a good reference from the following program

您可以从以下程序中获得很好的参考

# 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)