Trying To Take Size And Input Of A List In A Single Line
I want to input 'n+1' numbers from the user in a single line, the first number gives the size of the list, while the following numbers are the actual elements of the list. (n,listA
Solution 1:
I'm assuming you want this for code golfing purposes. This is AFAIK the shortest oneliner that will work:
n,*l=map(int,input().split()) # in: 3 6 71 51print(n) # out: 3print(l) # out: [6, 71, 51]
Without using semicolons, I think the size of the input can only be restriced in one line using Python 3.8:
n,*l=list(map(int,i:=input().split()))[:int(i[0])+1] # in: 3 6 71 51 80 95print(n) # out: 3print(l) # out: [6, 71, 51]
Solution 2:
[[n],listA] = [list(map(int,i.split())) for i in input().split(' ',1)]
split(' ',1) will split first occurrence, so an input like 4 12 43 23 56 will split to '4', '12 43 23 56',
then preform another spiting with mapping the output will be [[4], [12, 43, 23, 56]]
then we can unpack the value again [[n],listA]
.
however i suggest to neglect the size from input and taking list of numbers and by using size = len(listA)
we can determine the size.
Post a Comment for "Trying To Take Size And Input Of A List In A Single Line"