python - Search for same values in 2 lists but only once if duplicate -


lst1 = [0.0, 2.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, 8.0, 10.0, 10.0, 10.0, 13.0] lst2 = [4.,  8.] [i i, j in enumerate(lst1) if j in lst2] 

i return of:

[4, 8, 9] 

what want achieve want return of:

[4, 8] 

because 8.0 repeated in lst1, want once. best way of achieving this?

the best way can readily think of is, maintain set of seen numbers , if number not in seen set add index result , number seen set.

result, seen = [], set() index, item in enumerate(lst1):     if item not in seen , item in lst2:         result.append(index)         seen.add(item) print(result) # [4, 8] 

note 1: use set maintaining seen items, because lookups fast (constant time lookup)

note 2: if lst2 going long list, better convert set, item in lst2 lookup happen in constant time. actual code becomes,

result, seen, set2 = [], set(), set(lst2) index, item in enumerate(lst1):     if item not in seen , item in set2:         result.append(index)         seen.add(item) print(result) # [4, 8] 

this give better performance first version, if lst2 going lengthy one.

an alternate solution inspired dsm's solution is, building reverse index dictionary, this

>>> reverse_indexes = {lst1[i]: index in xrange(len(lst1) - 1, -1, -1)} 

then can lookup this

>>> [reverse_indexes[item] item in lst2 if item in reverse_indexes] [4, 8] 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -