Search code examples
pythonlistcomparison

How do I compare two unordered lists of lists with unordered lists inside of them?


How do I compare two unordered lists of lists with unordered lists inside of them?

Assume that the lists within the two lists of lists are not necessarily in the same order. Also assume that the order of items in a given lists within the lists of lists are not necessarily in the same order. An example is shown below:

dummy_list_A =  [['A'], ['B'], ['C', 'D']]
dummy_list_B =  [['B'], ['A'], ['D', 'C']]

I have already looked on Stack Overflow for answers to questions such as Test if two lists of lists are equal and none of them worked. You can see for yourself below that the most common answers to comparing lists of lists does not work for my scenario.

print sorted(dummy_list_A) == sorted(dummy_list_B)
False

print set(map(tuple,dummy_list_A)) == set(map(tuple,dummy_list_B))
False

print ((len(dummy_list_A) == len(dummy_list_B)) and (all(i in dummy_list_B for i in dummy_list_A)))
False

Solution

  • You could simply sort the elements in the sublists, sort the sublists and compare the two lists.

    >>> dummy_list_A =  [['A'], ['B'], ['C', 'D']]
    >>> dummy_list_B =  [['B'], ['A'], ['D', 'C']]
    >>> sorted(map(sorted, dummy_list_A))
    [['A'], ['B'], ['C', 'D']]
    >>> sorted(map(sorted, dummy_list_B))
    [['A'], ['B'], ['C', 'D']]
    >>> def signature(l):
    ...   return sorted(map(sorted, l))
    ... 
    >>> signature(dummy_list_A) == signature(dummy_list_B)
    True