簡體   English   中英

如何在 Python 中創建 function 以確定列表是否已排序?

[英]How to create a function in Python to determine if list is sorted or not?

我被要求檢查是否使用 function 對列表進行了排序,但是我在不使用輸入 ZC1C425268E68385D1AB50741C 的情況下在 function 中定義參數 (lst) 時遇到了問題它說 lst 是未定義的,但我不確定如何在不使用輸入 function 的情況下更改它

def is_sorted(lst):
    lst  = []
    flag = 0
    lst1 = lst[:]
    lst1.sort()
    if (lst1 == lst):
        flag = 1
    if (flag) :
        return "True"
    else:
        return "False"

print (is_sorted(lst))

錯誤是沒有定義lst

在您第一次調用lst時(在print (is_sorted(lst))行中),您實際上並沒有給lst一個值。 在 print() 之前,您需要一個lst = [1,2,3] (或其他東西)。

但是,您可能想多了這個 function。 我添加了一個簡化版本,使用 Python 的sorted function 作為比較器。

def is_sorted(lst):
    if (lst == sorted(lst)) or (lst == sorted(lst, reverse = True)):
        return "True"
    else:
        return "False"

lst = [3,1,2]
print (is_sorted(lst))
lst = [1,2,3]
print (is_sorted(lst))
lst = [3,2,1]
print (is_sorted(lst))

OUTPUT:

False
True
True

為了理解錯誤,必須了解參數和 function 的 arguments 之間的區別。

有用的材料:

Python 詞匯表:參數參數

Python FAQ: arguments和參數有什么區別

暫無
暫無

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

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