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