Test if two lists of lists are equal

匿名 (未验证) 提交于 2019-12-03 09:18:39

问题:

Say I have two lists of lists in 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?

Note to do this for ordinary lists see here, however this uses set which does not work for lists of lists.

回答1:

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

Result:

True


回答2:

Set doesn't work for list of lists but it works for list of tuples. Sou you can map each sublist to tuple and use set as:

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


回答3:

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

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!