I want to compare two Python lists, \'A\' and \'B\' in such a manner that I can find all elements in A which correspond to the same number in B
An alternative using collections.defaultdict
:
import collections as ct
dd = ct.defaultdict(list)
for a, b in zip(A, B):
dd[b].append(a)
dd
# defaultdict(list, {1: [7, 16], 2: [5, 12], 3: [9, 8], 4: [25]})
Sample of printed results:
for k, v in sorted(dd.items()):
print("{} corresponding to the number {} of listB".format(v, k))
# [7, 16] corresponding to the number 1 of listB
# [5, 12] corresponding to the number 2 of listB
# [9, 8] corresponding to the number 3 of listB
# [25] corresponding to the number 4 of listB