Nat*_*per 2 python dictionary python-3.x
我知道这是python 2中一种非常有效的方式,可以交叉2个词典
filter(dict_1.has_key, dict_2.keys())
Run Code Online (Sandbox Code Playgroud)
但是has_key()
从Python3中删除了,所以我无法真正使用快速filter()
和has_key()
功能.我现在正在做的是:
[key for key in dict_2 if key in dict_1]
Run Code Online (Sandbox Code Playgroud)
但它似乎有点笨拙,除了没那么可读.这真的是python3的最快新方式,还是使用更快,更清洁的方式filter()
?
如您所希望的那样,您可以这样做:
d1 = {1 : 1, 2 : 2}
d2 = {1 : 3, 2 : 4, 3 : 5}
common = list(d1.keys() & d2.keys())
print(common)
Run Code Online (Sandbox Code Playgroud)
产量
[1, 2]
Run Code Online (Sandbox Code Playgroud)
has_key
您可以in
在Python 3.x中使用运算符,而不是在Python 2 中.有了filter
,它在3.x中提供了一个惰性迭代器,你可以使用dict.__contains__
.也没有必要打电话dict.keys
:
res = filter(dict_1.__contains__, dict_2) # lazy
print(list(res))
# [2, 3]
Run Code Online (Sandbox Code Playgroud)
一种等效但不太美观lambda
的解决方案:
res = filter(lambda x: x in dict_1, dict_2) # lazy
Run Code Online (Sandbox Code Playgroud)
生成器表达式是第三种选择:
res = (x for x in dict_2 if ix in dict_1) # lazy
Run Code Online (Sandbox Code Playgroud)
对于非惰性方法,您可以使用set.intersection
(或其语法糖&
):
res = set(dict_1) & set(dict_2) # {2, 3}
Run Code Online (Sandbox Code Playgroud)