Running across a subset of a list in python -
is possible run through subset in python list?
i have following problem, have 2 lists, list1
long , list2
quite short. now, want check elements of list2
in list1
. current version looks this:
for item in list1: if item in list2: #
this takes long time. possible subset , run through list?
i need many times.
if list elements hashable, can find intersection using sets:
>>> x in set(list2).intersection(list1): print x
if not hashable, can @ least speed-up search sorting shorter list , doing bisected lookups:
>>> bisect import bisect_left >>> list2.sort() >>> n = len(list2) >>> x in list1: = bisect_left(list2, x) if != n , list2[i] == x: print x
if data elements neither hashable nor sortable, won't able speed-up original code:
>>> x in list1: if x in list2: print x
the running time of set-intersection approach proportional sum of lengths of 2 lists, o(n1 + n2)
. running time of bisected-search approach o((n1 + n2) * log(n2))
. running time of original brute-force approach o(n1 * n2)
.
Comments
Post a Comment