hra*_*cek 3 python optimization input python-3.x
我正在尽可能地为条件输入制作最短的代码.
条件:数字应大于0.
输入:第一个数字确定下一个输入的数量.
例如:
4
1
-2
3
-4
Run Code Online (Sandbox Code Playgroud)
所以我想追加list()只有1和3.
这是我的代码:
n=int(input())
t=[]
for i in range(n):
x = int(input())
if(x>0):
t.append(x)
print(t)
Run Code Online (Sandbox Code Playgroud)
我想知道它是否可以缩短
我的想法,但它没有像我预期的那样工作 - "语法错误":
n=int(input())
t=[x=int(input()) for x in range(n) if(x)>0)]
print(t)
Run Code Online (Sandbox Code Playgroud)
编辑:忘了.我正在使用python3.1 ...
这是一种方法:
[x for x in (int(input()) for _ in range(int(input()))) if x > 0]
Run Code Online (Sandbox Code Playgroud)