簡體   English   中英

檢查列表是升序還是降序(使用 FOR)

[英]Check if list is Ascending OR Descending (using FOR)

所以我在我的大學里被設置了一個任務,我想檢查一個列表是否實際上是排序的(升序或降序)。 但我必須使用'for'。 (最近剛學了for和list,一定要實踐一下)

到目前為止,這是我所擁有的,我能夠確認列表是否正在降序,但不是降序或升序:

A=[10,9,8,3,1,0]

def order(A):
    for i in range(len(A) - 1): 
        if ((A[i]>A[i+1])) :
            return False
    return True

您需要以這種方式創建一個算法,以便其他參數之前的結果是唯一的!

對於升序,檢查當前項與下一次的減法是否大於0,如果是,則不升序排序。

對於降序,檢查當前項與下一次的減法是否小於0,如果是,則不進行降序排序。

試試這個:

def order(A) # Ascending order
    for i in range(len(A) - 1):
        if A[i] - A[i+1] > 0:
            return False
    return True

def order(A) # Descending order
    for i in range(len(A) - 1):
        if A[i] - A[i+1] < 0:
            return False
    return True

這是一個簡單的方法來返回列表是升序、降序還是兩者都不是。

def order(A):
if A == sorted(A,reverse=False):
    return 'Ascending'
elif A == sorted(A,reverse=True):
    return 'Descending'
else:
    return 'Neither'

這是一個帶有簡單輸入的示例輸出。

>> a = [2,5,4,7,1]
>> b = [1,3,5,7,9]
>> c = [9,6,3,1,0]
>> print(order(a), order(b), order(c))
out: Neither Ascending Descending

這個函數的好處是我們不必分析單個元素,我們只需要使用內置函數來分析整個列表。

這可能有幫助:

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

這里我們要做的是維護兩個布爾標志ascdesc ,它們將表示傳遞的列表是升序還是降序。

然后,對於每個連續的一對列表中的號碼,計算它們的差if someList[idx] - someList[idx - 1] >= 0:然后我們和desc標志與False ,反之亦然在else情況下。

直觀地說,這段代碼的作用是這樣的:如果一個序列是升序的,那么每對連續的數字都會有它們的差大於零,例如:考慮這個序列[a, b, c, d, e, f]其中所有字符都表示數字並假設此序列按升序排列,即a <= b <= c <= d <= e <= f ,如果我們考慮所有連續的數字對,即(a, b), (b, c), (c, d), and so on..並計算這些對中的每一個的差異,即ba, cb, dc and so on..那么every difference will be >= 0ba >= 0 and cb >= 0 and dc >= 0 and ed >= 0 and fe >= 0這是上面代碼中asc布爾標志表示的條件。 可以對desc布爾標志進行類似的解釋。

如果您在仍然使用for循環的同時想要上述代碼的較小版本,請使用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

如果listascendingdescending您想返回True

這使得code真正*可讀**:

def order(lst):
    ascending = descending = True
    for i in range(len(lst) - 1): 
        if lst[i] > lst[i+1] :
            ascending = False
        elif lst[i] < lst[i+1] :
            descending = False
    return ascending or descending

我們首先定義2 boolean variables設置為True - ascendingdescending 然后,我們通過循環lst (我給了function更明智的param名)和檢查ifindex小於下。 如果是,我們可以將ascending variable設置為False (因為lst現在不能再ascending). Else, if the next index is greater than the current ascending). Else, if the next index is greater than the current索引, we set降序, we set to False`。

最后,最后我們return如果lstascending or descending


一些例子:

>>> order([1,2,3,4])
True
>>> order([1,2,3,2])
False
>>> order([3,2,1,0])
True
>>> order([3,2,1,4])
False

希望這有幫助! (順便說一句,如果您有興趣,您可以在one-line執行相同的function ):

def order(lst):
    return lst == sorted(lst) or lst == sorted(lst)[::-1]
def descending(l):
  x=0
  if len(l)<= 1 or (len(l) == 2 and l[0] >= l[1]):
    return True
  else:
    if l[0]<=l[1]:
      return descending(l[1:])
    else:
      return False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM