简体   繁体   English

测试两个列表是否相等

[英]Test if two lists of lists are equal

Say I have two lists of lists in Python, 假设我在Python中有两个列表列表,

l1 = [['a',1], ['b',2], ['c',3]]
l2 = [['b',2], ['c',3], ['a',1]]

What is the most elegant way to test they are equal in the sense that the elements of l1 are simply some permutation of the elements in l2 ? l1的元素只是l2元素的一些排列的意义上,最优雅的方法是测试它们是否相等?

Note to do this for ordinary lists see here , however this uses set which does not work for lists of lists. 注意做这个普通列表在这里看到的 ,然而,这使用set不为列表的列表的工作。

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

Result: 结果:

True

Set doesn't work for list of lists but it works for list of tuples. Set不适用于列表列表,但它适用于元组列表。 Sou you can map each sublist to tuple and use set as: 你可以map每个子列表map到元组并使用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

For one liner solution to the above question, refer to my answer in this question 对于上述问题的一个班轮解决方案,请参阅我在这个问题中的答案

I am quoting the same answer over here. 我在这里引用相同的答案。 This will work regardless of whether your input is a simple list or a nested one. 无论您的输入是简单列表还是嵌套列表,这都将起作用。

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 :- 让这两个列表是list1和list2,你的要求是确保两个列表是否具有相同的元素,然后按照我的说法,以下将是最好的方法: -

 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 ie whether all the elements of list1 are in list2 and vice-verse. 上面的代码将根据您的需要工作,即list1的所有元素是否在list2和反之亦然。 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 :- 但是如果你想检查list1中是否存在list1的所有元素,那么你只需要使用下面的代码: -

 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. 不同的是,如果list2包含一些额外的元素以及list1的所有元素,则后者将打印True。 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. 简单来说,它将确保list1的所有元素都应该出现在list2中,无论list2是否有一些额外的元素。

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

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