python - Efficiently find overlap of a lists of tuples -
i have bunch of lists, each composed of tuples.
a = [(1,2,3),(4,5,7),(8,9,10),(5,6,2)] b = [(1,3,6),(4,2,8),(3,6,7),(5,2,8)] c = [(6,2,3),(1,7,2),(5,7,2),(7,2,7)]
i need find group of tuples such first element of tuple appears in every list. (i know confusing) above example, overlap be:
overlap = [(1,2,3),(1,3,6),(1,7,2),(5,6,2),(5,2,8),(5,7,2)]
this because tuple number '1' in first element of tuple appears in every list. same number '5'.
what best way this?
i have working code, feel there better way this.
big_list = [a,b,c] overlap = [] all_points = list(set([item item in big_list])) (f,s,t) in all_points: in_all = true lest in big_list: present = false (first, second, third) in lest: if first == f: present = true if not present: in_all = false if in_all: overlap.append((f,s,t))
you can use set intersection this:
>>> itertools import chain >>> def get_first(seq): return (x[0] x in seq) >>> common = set(get_first(a)).intersection(get_first(b), get_first(c))
now common
contains:
>>> common set([1, 5])
now can loop on individual items a, b , c , choose tuples first item found in common:
>>> [x x in chain(a, b, c) if x[0] in common] [(1, 2, 3), (5, 6, 2), (1, 3, 6), (5, 2, 8), (1, 7, 2), (5, 7, 2)]
sort first item:
>>> operator import itemgetter >>> sorted((x x in chain(a, b, c) if x[0] in common), key=itemgetter(0)) [(1, 2, 3), (1, 3, 6), (1, 7, 2), (5, 6, 2), (5, 2, 8), (5, 7, 2)]
Comments
Post a Comment