测试两个列表的列表是否相等

5
假设我在Python中有两个列表的列表,
l1 = [['a',1], ['b',2], ['c',3]]
l2 = [['b',2], ['c',3], ['a',1]]

什么是测试它们是否相等的最优雅方式,即 l1 的元素只是 l2 中元素的某种排列顺序?
请注意,对于普通列表,请参见此处,但这使用了不适用于列表的 set

如果一个内部列表是另一个的排列,它们被认为是“相等”的吗?在两种情况下,重复怎么办? - Kyle Strand
3个回答

16
l1 = [['a',1], ['b',2], ['c',3]]
l2 = [['b',2], ['c',3], ['a',1]]
print sorted(l1) == sorted(l2)

结果:

True

3

set 不能用于列表的列表,但可以用于元组的列表。因此,您可以将每个子列表映射到元组并使用 set,如下所示:

>>> l1 = [['a',1], ['b',2], ['c',3]]
>>> l2 = [['b',2], ['c',3], ['a',1]]
>>> print set(map(tuple,l1)) == set(map(tuple,l2))
True

2
这将丢失有关计数的信息:换句话说,如果l1有10个['a', 1]子列表,而l2只有1个,则仍然会说它们相等。(也许这是OP想要的,但根据“排列”我猜测不是这样。) - DSM
这可能不是 OP 想要的,但这正是我所需要的。因为在我的情况下,我没有重复项,而且列表内部也没有排序。 - Òscar Raya

0

针对上述问题的一行解决方案,请参考此问题中我的答案

我在这里引用同样的答案。无论您的输入是简单列表还是嵌套列表,此方法都适用。

let the two lists be list1 and list2, and your requirement is to ensure whether two lists have the same elements, then as per me, following will be the best approach :-

if ((len(list1) == len(list2)) and
   (all(i in list2 for i in list1))):
    print 'True'
else:
    print 'False'

The above piece of code will work per your need i.e. whether all the elements of list1 are in list2 and vice-verse. Elements in both the lists need not to be in the same order.

But if you want to just check whether all elements of list1 are present in list2 or not, then you need to use the below code piece only :-

if all(i in list2 for i in list1):
    print 'True'
else:
    print 'False'

The difference is, the later will print True, if list2 contains some extra elements along with all the elements of list1. In simple words, it will ensure that all the elements of list1 should be present in list2, regardless of whether list2 has some extra elements or not.


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