尝试在一行中获取列表的大小和输入 [英] Trying to take size and input of a list in a single line
问题描述
我想在一行中输入用户的"n + 1"个数字,第一个数字给出列表的大小,而后面的数字是列表的实际元素.
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)=(int(input()),list(map(int,input().split())))
这有效,但是我必须在输入第一个数字(大小)后按Enter键,否则会出现错误.我希望此操作无需输入即可. 示例-4 12 43 23 56 所以大小= 4 list = [12,43,23,56]
This works but I have to hit enter after giving the first number (the size) otherwise I get an error. I want this done without enter. Example - 4 12 43 23 56 So size=4 list=[12,43,23,56]
推荐答案
我假设您出于代码打高尔夫的目的而希望使用它.这是AFAIK可以使用的最短的oneliner:
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 51
print(n) # out: 3
print(l) # out: [6, 71, 51]
在不使用分号的情况下,我认为使用Python 3.8只能将输入的大小限制为一行:
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 95
print(n) # out: 3
print(l) # out: [6, 71, 51]
这篇关于尝试在一行中获取列表的大小和输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!