简体   繁体   中英

How to check if elements of one list/dict present in another list/dict in python

here is a scenario, I am checking if elements of A are present in B. while this code works, it takes a lot of time when I read through million of lines. The efficient way would be to make each list in A and B as dictionary and look if they are present in each other. But I am not able to think of a simple way to do dictionary lookup. That is for each key-value pair in dict A, I want to check if that key-value pair is present in dictB

A = [['A',[1,2,3]],['D',[3,4]],['E',[6,7]]]

B=  [['A',[1,2,3]],['E',[6,7]],['F',[8,9]]]

count = 0

for line in A:

  if len(line[1]) > 1:

     if line in B:

       count = count + 1

print count
  1. convert the lists to tuples
  2. convert the list of tuples to a set
  3. intersect the two sets
  4. print the length of the intersection

Example:

A = [['A',[1,2,3]],['D',[3,4]],['E',[6,7]]] 
B = [['A',[1,2,3]],['E',[6,7]],['F',[8,9]]]

A_set = set((a, tuple(b)) for a, b in A)
B_set = set((a, tuple(b)) for a, b in B)
print len(A_set & B_set)

You could always try with a list comprehension and work your way up using this as a basis:

a = [[1], [5], [7]]
b = [[5], [7], [0]]
r = [x for x in a if x in b]

Make A and B into dictionaries:

dA = dict(A)
dB = dict(B)

Then, just check that the keys and values match:

count = 0
for k,v in dA.iteritems():
    if dB.get(k) == v:
        count += 1

You will need to do some pre-processing on B, so it's elements are immutable.

def deep_tuple(x):
    if type(x) in [type(()), type([])]:
        return tuple(map(deep_tuple,x))
    return x


A = ['A',[1,2,3]],['D',[3,4]],['E',[6,7]]
B = ['A',[1,2,3]],['E',[6,7]],['F',[8,9]]]
B = set(deep_tuple(B))
count = 0
for line in A:
  if len(line[1]) > 1:
     if line in B: 
       count = count + 1
print count

Make B into a set. Lookup in a set is O(1), as compared to O(|B|) otherwise. The overall complexity of this operation will be proportional to O(|A|).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM