[英]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. 这是一个场景,我正在检查A中的元素是否存在于B中,而这段代码可以工作,当我阅读数百万行时需要花费大量时间。 The efficient way would be to make each list in A and B as dictionary and look if they are present in each other. 有效的方法是将A和B中的每个列表作为字典,并查看它们是否存在于彼此中。 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 这是针对dict A中的每个键值对,我想检查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
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: 使A
和B
成为词典:
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. 你需要对B做一些预处理,所以它的元素是不可变的。
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. 将B组成一组。 Lookup in a set is O(1), as compared to O(|B|) otherwise. 一组中的查找是O(1),否则与O(| B |)相比。 The overall complexity of this operation will be proportional to O(|A|). 该操作的总体复杂度将与O(| A |)成比例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.