使用Python 3中的列表理解功能,从单行输入中读取一个整数列表以及一个范围 [英] Read an integer list from single line input along with a range using list comprehension in Python 3
问题描述
如何在Python 3中从单行输入以及范围读取整数列表?
要求:读取给定列表的整数值,该整数值与单行输入之间用空格隔开,但具有给定大小的范围.
Requirement: reading integer values for a given list separated by a space from single line input but with a range of given size.
示例:
范围= 4
然后列表大小= 4
然后从大小为4的一行中读取输入列表
Then read the input list from a single line of size 4
我在下面的列表理解语句中进行了尝试,但是它是从4行读取一个列表[即创建4个列表,每个列表代表给定行的值],而不是仅读取1个大小为4的列表
I tried below list comprehension statement, but it is reading a list from 4 lines [i.e creating 4 lists with each list representing values from a given line] instead of reading only 1 list with a size of 4
no_of_marks = 4
marksList = [list(int(x) for x in input().split()) for i in range(no_of_marks)]
有人可以帮助我实现我的要求吗?
推荐答案
您可以直接使用 str.split
,将 no_of_marks
传递为 maxsplit 参数:
You can use str.split
directly, passing the no_of_marks
for being maxsplit parameter:
no_of_marks = 4
res = [int(x) for x in input().split(" ", no_of_marks)]
这里有在线示例
这篇关于使用Python 3中的列表理解功能,从单行输入中读取一个整数列表以及一个范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!