[英]How do I compare the value of x with the previous value?
how do I compare the values of x so that they are in increasing order我如何比较 x 的值,以便它们按递增顺序排列
n = 5
i = 1
while i <= n:
x = int(input())
i = i + 1
n = 5
i = 1
prev = float('-inf')
while i <= n:
x = int(input())
if x < prev:
print(f'{x} is lesser than {prev}!')
break
prev = x
i += 1
You can only compare values to previous values, so you'll have to keep them around.您只能将值与以前的值进行比较,因此您必须保留它们。 Since you ask about "increasing order", it appears you want to collect all the inputs:
由于您询问“增加订单”,因此您似乎想要收集所有输入:
n = 5
i = 1
x = []
while i <= n:
x += [int(input())]
i = i + 1
x = sorted(x)
x = []
sets up x
as an empty list. x = []
将x
设置为空列表。 x += [int(input())]
does the same as your command, but instead of assigning the result directly to x
, it puts it in a small list and adds that to the end of x
. x += [int(input())]
与您的命令执行相同的操作,但不是将结果直接分配给x
,而是将其放在一个小列表中并将其添加到x
的末尾。 The final command just sorts the list in one go.最后一个命令只是一次性对列表进行排序。
There's many ways to construct a list though.有很多方法可以构建一个列表。 Instead of
x += [int(input())]
, you might prefer something like x.append(int(input()))
.而不是
x += [int(input())]
,您可能更喜欢x.append(int(input()))
。 That's a matter of style, mostly.这主要是风格问题。
While the previous answers are all correct, I prefer:虽然以前的答案都是正确的,但我更喜欢:
x = <some random value>
while i <= n:
prev_x, x = x, int(input())
...
This makes it immediately clear that at the same time x
is getting a new value, prev_x
is getting its previous value.这立即清楚地表明,在
x
获得新值的同时, prev_x
正在获得其先前的值。
Others' sensibilities may differ.其他人的感受可能有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.