如何按照输入的顺序打印整数?
第一个输入x应该是它接受的y整数的个数,然后以相同的顺序打印所有大于0但小于50的y。
例如:
input:
4
5
8
52
10
output:
5
8
10
我使用了如下所示的列表。有更简单的方法吗?
x = int(input())
lst = []
while len(lst) <= x-1:
i = int(input())
i = lst.append(i)
for y in lst:
if 0 < y < 50:
print(y)
您的代码可以缩小为:
lst = [int(input()) for _ in range(int(input()))]
print(*[x for x in lst if 0 < x < 50], sep='n')
同样,将append
(None
)的值赋给一个变量是没有意义的。
或:
lst = [int(input()) for _ in range(int(input()))]
for x in lst:
if 0 < x < 50:
print(x)
使用列表推导式和for循环-
x = int(input())
lst = [int(input()) for i in range(x)]
for y in lst:
if 0 < y < 50:
print(y)
我发现有一件事没有多大意义,那就是:
while len(lst) <= x-1:
i = int(input())
i = lst.append(i) #What the point of making i the result of append?
你可以马上做lst.append(i)
。
甚至lst.append(int(input()))
。
你也可以简单地做while len(lst) < x
,不需要<= x - 1
。
其余的代码对我来说是完美的。