These are the two lists, both of which have the same number of elements:
JavaScript
x
4
1
list1 = [['23', '30', 'pm'], ['01', '00', 'am'], ['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]
2
3
list2 = [['23', '30', 'pm'], ['01', '00', 'am'], ['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]
4
I try with this:
JavaScript
1
6
1
list1 = list(list1 - list2)
2
list2 = list(list2 - list1)
3
4
print(repr(list1))
5
print(repr(list2))
6
but I get this error when trying to subtract the elements that are the same in both lists
JavaScript
1
2
1
TypeError: unsupported operand type(s) for -: 'list' and 'list'
2
I need the lists to be like this, that is, within each of them there are only those elements that are different:
JavaScript
1
4
1
list1 = [['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]
2
3
list2 = [['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]
4
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)
Advertisement
Answer
You should use zip
to iterate the lists in parallel, and another zip
to separate the output back in two lists:
JavaScript
1
2
1
l1,l2 = map(list, zip(*((a,b) for a,b in zip(list1, list2) if a!=b)))
2
Output:
JavaScript
1
6
1
# l1
2
[['1', '00', 'am'], ['1', '00', 'pm'], ['1', '', 'pm'], ['5', '', 'pm']]
3
4
# l2
5
[['01', '00', 'am'], ['01', '00', 'pm'], ['01', '00', 'pm'], ['05', '00', 'pm']]
6