问题
How to read an integer list from single line input along with a range in 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.
example:
Range = 4
Then list size = 4
Then read the input list from a single line of size 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)]
Can someone help me in achieving my requirement?
回答1:
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)]
Here you have the live example
回答2:
Split the string, slice it to only take the first n words, and then turn them into integers.
marks = [int(x) for x in input().split()[:n]]
This will not fail if the input has fewer than n integers, so you should also check the length of the list
if len(marks) < n:
raise ValueError("Not enough inputs")
来源:https://stackoverflow.com/questions/51847501/read-an-integer-list-from-single-line-input-along-with-a-range-using-list-compre