Read an integer list from single line input along with a range using list comprehension in Python 3

时光毁灭记忆、已成空白 提交于 2020-01-30 09:17:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!