这可能会有所帮助:
A=[10,9,8,3,1,0]
B=[1,9,18,33,41,50]
C=[1, 1, 1, 1, 1]
D= [1]
E=[1, 2, 3, 2, 1]
F =[]
def order(someList):
asc = True
desc = True
for idx in range(1, len(someList)):
if someList[idx] - someList[idx - 1] >= 0:
asc = asc & True
desc = desc & False
else:
desc = desc & True
asc = asc & False
if asc and not desc:
return "list is in ascending order"
elif desc and not asc:
return "list is in descending order"
else:
return "list is in no order"
print(order(A))
print(order(B))
print(order(C))
print(order(D))
print(order(E))
print(order(F))
当执行时,这段代码的输出是:
list is in descending order
list is in ascending order
list is in ascending order
list is in no order
list is in no order
list is in no order
我们正在做的是维护两个布尔标志asc 和desc,这将表示传递的列表是升序还是降序。
然后,对于列表中的每一对连续数字,我们计算它们的差异 if someList[idx] - someList[idx - 1] >= 0: 然后我们将 desc 标记为 False,反之亦然 else 情况。
直观地说,这段代码所做的事情如下:
如果一个序列是升序的,那么每对连续的数字的差值都将大于零,例如:考虑这个序列[a, b, c, d, e, f],其中所有字符都代表数字并假设这个序列是升序的情况,即@ 987654330@,如果我们考虑所有连续的数字对,即(a, b), (b, c), (c, d), and so on..,并计算每对数字的差异,即b-a, c-b, d-c and so on..,那么every difference will be >= 0,即b-a >= 0 and c-b >= 0 and d-c >= 0 and e-d >= 0 and f-e >= 0,这就是asc所代表的条件上面代码中的布尔标志。 desc boolean flag 可以考虑类似的解释。
如果你想要更小的版本上面的代码仍然使用for循环,那么使用这个:
A=[10,9,8,3,1,0]
B=[1,9,18,33,41,50]
C=[1, 1, 1, 1, 1]
D= [1]
E=[1, 2, 3, 2, 1]
F = []
def order(someList):
results = [True if second >= first else False for first, second in zip(someList, someList[1:])]
if any(results) and all(results):
return "ascending order"
elif not any(results) and not all(results):
return "descending order"
else:
return "no order"
print(order(A))
print(order(B))
print(order(C))
print(order(D))
print(order(E))
print(order(F))
并为此输出
descending order
ascending order
ascending order
no order
no order
no order