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

时间:2016-11-11 15:21:34

标签: python arrays list sorting tuples

我需要检查元组列表是否按元组的第一个属性排序。最初,我可以根据自己的排序检查此列表。比如......

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 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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))

答案 2 :(得分:0)

@joce已经提供an excellent answer(我建议接受一个,因为它更简洁,直接回答你的问题),但我想解决你原帖的这一部分:

  

列表的长度可能为5或可能为100,因此执行list1[0] == sortedlist1[0], and 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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

使用此:

sorted(list1) == sorted(list2)
相关问题