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

3

我需要检查一个元组列表是否按照元组的第一个属性排序。最初,我想将该列表与其已排序的副本进行比较,例如...

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]并不是一个好选择。谢谢。
5个回答

9
我相信你只需要执行list1 == sortedlist1,而无需逐个检查每个元素。

这是正确的,因为相似类型的序列支持迭代词典比较。请参见表格后面的注释此处。因此,相等比较会在序列中进行迭代,直到找到不同的一对或序列的末尾(前者返回False,后者返回True)。 - Pierce Darragh

1

@joce已经提供了一个很好的答案(我建议接受那个答案,因为它更简洁直接地回答了你的问题),但我想解决你原始帖子中的这部分:

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

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

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

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已经通过质量运算符==内置了这个功能。因此,只需要简单地写:

list1 == list2

0
如果你想检查一个列表是否已排序,一个非常简单的解决方案就会浮现在脑海中:
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

这样做的另一个优点是只需要遍历列表一次。如果你先对其排序再进行比较,你就至少需要遍历列表超过一次。
如果您仍想以这种方式执行,请使用另一种方法:
list1 = [(1, 2), (4, 6), (3, 10)]
sortedlist1 = sorted(list1, reverse=True)
all_equal = all(i[0] == j[0] for i, j in zip(list1, sortedlist1))

0
使用这个:
sorted(list1) == sorted(list2)

0
在Python 3.x中,您可以使用“eq”运算符检查两个元组列表a和b是否相等。
import operator

a = [(1,2),(3,4)]
b = [(3,4),(1,2)]
# convert both lists to sets before calling the eq function
print(operator.eq(set(a),set(b))) #True

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接