可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.