为什么有序列表不等于list.sort()?

时间:2019-03-22 13:49:28

标签: python

我有这段代码可以检查列表是否已订购。因此,我使用array == array.sort()来验证这种情况。我哪里出错了?

代码:

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]))

3 个答案:

答案 0 :(得分:1)

您应该改用sorted,因为它会返回已排序列表的副本。您还可以简化代码,因为比较返回一个布尔值:

def isOrdered(t):
    """
    t: list
    return True if the list is ordered in a growing sense
    """
    return t == sorted(t)

答案 1 :(得分:0)

array.sort()
内联工作,这意味着它不会返回任何内容。

相反,请制作副本,对副本进行排序,然后检查相似性。

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

答案 2 :(得分:0)

OP 如果列表的排列顺序越来越长,则返回True

因此

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 

输出

True
False
False
False