如何检查两个元组列表是否相同

2024-10-03 17:25:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要检查元组列表是否按元组的第一个属性排序。一开始,我不想把这张单子和它分类后的自己核对一下。比如。。。在

list1 = [(1, 2), (4, 6), (3, 10)]
sortedlist1 = sorted(list1, reverse=True)

我如何检查list1是否与sortedlist1相同?相同,如list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1]。在

该列表的长度可能为5或100,因此执行list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1]将不是一个选项,因为我不确定该列表有多长。 谢谢


Tags: andtrue列表属性排序选项分类单子
3条回答

我相信您可以只做list1 == sortedlist1,而不必单独查看每个元素。在

如果您想检查列表是否已排序,您会想到一个非常简单的解决方案:

last_elem, is_sorted = None, True
for elem in mylist:
    if last_elem is not None:
        if elem[0] < last_elem[0]:
            is_sorted = False
            break
    last_elem = elem

这样做的另一个好处是只需浏览一次列表。如果你要比这个列表大一点的话,你至少要比较一下。在

如果你还想这样做,这里有另一种方法:

^{pr2}$

@joce已经提供了an excellent answer(我建议接受这一条,因为它更简洁、更直接地回答了您的问题),但我想在您最初的帖子中提到这一部分:

The list may have a length of 5 or possibly 100, so carrying out list1[0] == sortedlist1[0], and list1[1] == sortedlist1[1] would not be an option because I am not sure how long the list is.

如果要比较两个列表中的每个元素,则不需要确切知道列表的长度。编程是关于懒惰的,所以你可以打赌没有一个好的程序员会手写出这么多的比较!在

相反,我们可以用索引遍历这两个列表。这将允许我们同时对两个列表中的每个元素执行操作。下面是一个例子:

def compare_lists(list1, list2):
    # Let's initialize our index to the first element
    # in any list: element #0.
    i = 0

    # And now we walk through the lists. We have to be
    # careful that we do not walk outside the lists,
    # though...
    while i < len(list1) and i < len(list2):
        if list1[i] != list2[i]:
            # If any two elements are not equal, say so.
            return False

    # We made it all the way through at least one list.
    # However, they may have been different lengths. We
    # should check that the index is at the end of both
    # lists.
    if i != (len(list1) - 1) or i != (len(list2) - 2):
        # The index is not at the end of one of the lists.
        return False

    # At this point we know two things:
    #  1. Each element we compared was equal.
    #  2. The index is at the end of both lists.
    # Therefore, we compared every element of both lists
    # and they were equal. So we can safely say the lists
    # are in fact equal.
    return True

也就是说,检查Python是否通过quality操作符==内置了此功能,这是一件非常常见的事情。因此,简单地写:

^{pr2}$

相关问题 更多 >