繁体   English   中英

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

[英]How to check if two lists of tuples are identical

我需要检查元组列表是否按元组的第一个属性排序。 最初,我想根据它的排序自我检查这个列表。 比如……

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]将不是一个选项,因为我不确定名单是。 谢谢

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

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

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

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

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

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

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

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

python 3.x ,您可以使用eq运算符检查两个元组ab列表是否相等

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

使用这个:

sorted(list1) == sorted(list2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM