[英]Why an ordered list isn't equal to list.sort()?
I have this code where I check if the list is ordered. 我在检查列表是否已订购的地方有此代码。 So I used array == array.sort()
to verify this condition. 所以我用array == array.sort()
来验证这种情况。 Where did I go wrong? 我哪里做错了?
Code: 码:
def isOrdered(t):
"""
t: list
return True if the list is ordered in a growing sense
"""
array = t
if array == array.sort(): #This doesn't work
return True
else:
return False
print(isOrdered([1, 2, 3, 4, 5]))
print(isOrdered([1, 3, 2, 4, 2]))
You should use sorted
instead, as it returns a copy of the list that is sorted. 您应该改用sorted
,因为它会返回已排序列表的副本。 You can also simplify your code a little bit, as comparison returns a boolean: 您还可以简化代码,因为比较返回一个布尔值:
def isOrdered(t):
"""
t: list
return True if the list is ordered in a growing sense
"""
return t == sorted(t)
array.sort()
works inline, meaning it doesn't return anything. 内联工作,这意味着它不返回任何内容。
Instead, make a copy, sort the copy then check for similarity. 而是制作副本,对副本进行排序,然后检查相似性。
def isOrdered(t):
"""
t: list
return True if the list is ordered in a growing sense
"""
t_copy = t[:]
t_copy.sort()
return t_copy == t
OP : return True if the list is ordered in a growing sense OP : 如果列表的排列顺序越来越长,则返回True
Hence : 因此 :
def isOrdered(t):
"""
t: list
return True if the list is ordered in a growing sense
"""
res = sorted(t) # check if the lst is soreted
if res:
if len(t) == len(set(t)): # ensure no duplicates in the lst
return True
else:
return False # duplicate means list is not in growing sense
else:
return False
print(isOrdered([1, 2, 3, 4, 5])) # Valid list with Growing sense
print(isOrdered([1, 1, 2, 3, 4, 5])) # Invalid list with dupes
print(isOrdered([1, 3, 2, 4, 2])) # Invalid list not sorted
print(isOrdered([1, 2, 3, 4, 5, 1])) # Invalid list with declining
OUTPUT : 输出 :
True
False
False
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.