Home > Enterprise >  How to remove from these 2 lists of lists the possible lists that appear in both lists of lists?
How to remove from these 2 lists of lists the possible lists that appear in both lists of lists?

Time:08-22

These are the two lists, both of which have the same number of elements:

list1 = [['23', '30', 'pm'], ['01', '00', 'am'], ['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]

list2 = [['23', '30', 'pm'], ['01', '00', 'am'], ['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]

I try with this:

list1 = list(list1 - list2)
list2 = list(list2 - list1)

print(repr(list1))
print(repr(list2))

but I get this error when trying to subtract the elements that are the same in both lists

TypeError: unsupported operand type(s) for -: 'list' and 'list'

I need the lists to be like this, that is, within each of them there are only those elements that are different:

list1 = [['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]

list2 = [['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]

How could I achieve this? (if possible without using additional libraries, although if there is no other way I would have no problem using them)

CodePudding user response:

You should use zip to iterate the lists in parallel, and another zip to separate the output back in two lists:

l1,l2 = map(list, zip(*((a,b) for a,b in zip(list1, list2) if a!=b)))

Output:

# l1
[['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]

# l2
[['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]

CodePudding user response:

Assuming that the two lists are paired correctly, you could use a zip in a list comprehension.

[[i,j] for i,j in zip(list1,list2) if i!=j]

  • Related