Test if two lists of lists are equal - python

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.

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

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.

Related

How do I check if a list contains all the elements of another list in Python? It's not working [duplicate]

This question already has answers here:
Checking if List contains all items from another list
(3 answers)
Closed 1 year ago.
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = item in List2 for item in List1
if check is True:
print("The list {} contains all elements of the list {}".format(List1, List2))
Why is this damn thing not working? Also is checkif = item in list2 for item in list1 a list comprehension or what?
Someone please correct my code, thanks.
I think you want all:
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = all(item in list1 for item in list2)
Also, you need to swap list1 and list1 to get the result you describe in the print line.
You can use sets here and specifically check the relationship whether one of your sets is a subset of the other:
set(list2).issubset(list1) # True
To use this the first object must be a set hence set(list2) but the second can be any iterable. One caveat here is that since we're comparing sets, it will only check for unique elements, i.e. it will not care about repeated values.

Check if part of a multi-dimensional list is in a seperate muti-dimensional list

Here is some example code.
list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
list2 = [['three','b'],['four','a'],['five','b']]
for l in list1:
if l not in list2:
print(l[0])
and the output from this code.
one
two
three
because ['four','a'] does indeed appear in both lists.
What I am trying to do is check if just the first item of each entry within the first list appears in the second list, I have tried variations of the following
list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
list2 = [['three','b'],['four','a'],['five','b']]
for l in list1:
if l[0] not in list2:
print(l[0])
however, that code returns
one
two
three
four
though both 'three' and 'four' do appear in the second list.
I have used different methods before now to find the values that appear in only one of a pair of lists, then used that to make a master list that contains all possible values with no duplicates and I believe the same should be possible using this method but the syntax is a mystery to me. Where I am going wrong here?
You could use not any() and then you check specific requirements in the comprehension:
list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
list2 = [['three','b'],['four','a'],['five','b']]
for l in list1:
if not any(l[0] == l2[0] for l2 in list2):
print(l[0])
# one
# two
You could also use sets if order doesn't matter:
list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
list2 = [['three','b'],['four','a'],['five','b']]
set(l[0] for l in list1) - set(l2[0] for l2 in list2)
# {'one', 'two'}
you can use set operations
list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
list2 = [['three','b'],['four','a'],['five','b']]
result = set(i[0] for i in list1) - set(i[0] for i in list2)
print(result)
# output {'one', 'two'}

Making a filtered list with list comprehension not working

Basically, given a list l of letters, i wanted to filter a list of letters to include only one instance of said letters in a new list:
l2 = []
for i in l:
if i not in l2:
l2.append()
And i wanted to use list comprehension, so i wrote:
l2 = [i for i in l if i not in l2]
But it returns me an empty l2. I'm just starting to learn how to use list comprehension and i'm kinda tired so i can't see where or if i'm doing wrong :(
list comprehension will not be working in this case as it works on a saved state of variable.
So, earlier l2 was blank and that state would be considered in comprehending.
Hence, the output would contain all the elements.
What i could notice is you were trying to get unique elements of 'l'.
Either you can use,
l2 = set(l) # if rlist is required you can type cast it back to list like, l2 = list(set(l))
The list-comprehension here can't work, as l2 is updated only when the all list-comprehension stuff is done, there no idea of list-comp intermediate state
What you want is just a unique instance of each letter, in other words : a set
l2 = set(l)
l2 = list(set(l)) # if you really want a list at the end
The problem with your list comprehension is that it relies on the list l2, which itself is the target of the list comprehension.
Sometimes a list comprehension is not the best way to go, even though it is a nice tool.
For your purpose it is best to convert list l to a set (which does not have duplicates) and then convert back to a list, which can be assigned to your list l2:
l2 = list(set(l))

Nested 'any' and 'all' condition in Python

I have a list of lists
list1 = [['a','b','c'],['m','n','o'],['x','y','z']]
Now, I want to check if all elements of any one of these 'sub-lists' are present in an incoming list called list2.
For example, if
list2 = ['a','c','e','b'] #Code would return True as a,b,c all from list1[0] match
list2 = ['a','c','m','x','e'] # False as all elements from any one sub-list do not match
list2 = ['g','h','i','x','y','z'] # True as all elements from list1[2] matched
I know that this can be done using a nested all within any python function. If list1 was not a nested list, I would have used
result = any(elem in list2 for elem in list1) # To check for any one
or
result = all(elem in list2 for elem in list1) # To check for all
However, I am at loss to do a nested any/all type of list comprehension. Any guidance would be appreciated.
You can do a combination of any and all:
list1 = [['a','b','c'],['m','n','o'],['x','y','z']]
def test(l1, l2):
return any(all(x in l2 for x in sub) for sub in l1)
print(test(list1, ['a','c','e','b']))
print(test(list1, ['a','c','m','x','e']))
print(test(list1, ['g','h','i','x','y','z']))
Output:
True
False
True
The test means: if all x's of any of the sublists are in list2.
Why not make list2 a set and use set.issuperset to see if all elements are in list2
list2 = {'g','h','i','x','y','z'}
print(any(list2.issuperset(elem) for elem in list1))
#True
You can even make this more simple using map although the comprehension is more readable
any(map(list2.issuperset, list1))
If you go this route I suggest not using list2 as the name to avoid confusion

How to check if contents of two lists is same in python?

I have 3 lists :
list_1 = [1,2]
list_2 = [2,1]
list_3 = [1,2,3]
Note: numbers inside [] are the ids from Django Model
I want to test whether the contents (but not necessarily the order) of two lists are exactly the same. With reference to the 3 examples above:
Comparing list_1 and list_2
should return True,
but if I do validation between list_2 and list_3, or between list_1 and list_3,
then the result should be False.
How do I achieve this?
Thanks :D
I interpret your question as return true if the contents (but not necessarily order) of the lists are identical, otherwise return false. This can be solved by sorting both lists, then using the == for comparison. sorted() returns a list of integers in ascending order. This means that if the lists' contents are the same, sorted() returns identical lists.
def validation(list_1,list_2):
return sorted(list_1) == sorted(list_2)
This passes all of your test cases. I might have misunderstood your question, please clarify if that's the case.

Categories

Resources