Python mapping between lists for duplicates -
i have 2 parallel lists following:
list1 - list2 1 -------- 1 -------- b 1 -------- c 2 -------- d 2 -------- d 2 -------- d 2 -------- e 2 -------- 3 -------- 3 -------- l 3 -------- m
i looking fast way in python count how many attributes of list 2 map different attributes in list 1. in example ouput like:
a maps 1, 2, 3
use zip()
pair values both lists , collections.defaultdict()
produce mapping:
from collections import defaultdict mapping = defaultdict(set) v1, v2 in zip(list1, list2): mapping[v2].add(v1)
now have dictionary mapping values list 2 sets containing unique values list 1; can print these match sample output with:
for v2 in sorted(mapping): print '{} maps {}'.format(v2, ', '.join(map(str, sorted(mapping[v2]))))
for sample input, produces:
>>> mapping defaultdict(<type 'set'>, {'a': set([1, 2, 3]), 'c': set([1]), 'b': set([1]), 'e': set([2]), 'd': set([2]), 'm': set([3]), 'l': set([3])}) >>> v2 in sorted(mapping): ... print '{} maps {}'.format(v2, ', '.join(map(str, sorted(mapping[v2])))) ... maps 1, 2, 3 b maps 1 c maps 1 d maps 2 e maps 2 l maps 3 m maps 3
Comments
Post a Comment