如何从 Python 字典值中查找常见项目?
How do I find common items from Python dictionary values?
说,我有一本字典 D
:
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
现在我想从 D
的值中获取所有常见项目,即 2。
我尝试使用 set.intersection
但没有成功。
简单地说,使用set
的intersection
方法:
>>> set.intersection(*D.values())
{2}
D.values()
将 return 已设置的字典值列表,然后 *D.values()
将解压缩此列表并将其传递给 intersection
方法 set
class
如果您只是在每个字典中寻找共同的值,而不是在每个字典中寻找一个值,那么下面的代码将起作用!并不是说这是最快或最好的方法,但它确实有效!
Returns 嵌入字典中所有重复值的列表!
def findCommon(data):
flipped = {}
out = []
for i in data:
for value in data[i]:
if value not in flipped:
flipped[value] = [i]
else:
flipped[value].append(i)
for i in flipped:
if len(flipped[i]) > 1:
out.append(i)
return out
为了多样化,你也可以使用reduce()
:
>>> D = {'A': {1, 2, 3}, 'B': {2 ,4, 5}, 'C': {1, 2, 7}}
>>> reduce(lambda x, y: x & y, D.values()) # or use operator.and_ instead of lambda
{2}
reduce()
is a built-in function in Python 2.x, but needs to be imported from the functools
模块在 Python 3.x.
如果您使用 reduce
,最有效的方法是使用 operator.and_
from functools import reduce
from operator import and_
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
print(reduce(and_, D.values()))
但是set.intersection
将很难被击败:
In [89]: from functools import reduce
In [90]: from operator import and_
In [91]: timeit reduce(lambda x, y: x & y, D.values())
1000 loops, best of 3: 221 µs per loop
In [92]: timeit reduce(and_,D. values())
10000 loops, best of 3: 170 µs per loop
In [93]: timeit set.intersection(*D.values())
10000 loops, best of 3: 155 µs per loop
说,我有一本字典 D
:
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
现在我想从 D
的值中获取所有常见项目,即 2。
我尝试使用 set.intersection
但没有成功。
简单地说,使用set
的intersection
方法:
>>> set.intersection(*D.values())
{2}
D.values()
将 return 已设置的字典值列表,然后 *D.values()
将解压缩此列表并将其传递给 intersection
方法 set
class
如果您只是在每个字典中寻找共同的值,而不是在每个字典中寻找一个值,那么下面的代码将起作用!并不是说这是最快或最好的方法,但它确实有效! Returns 嵌入字典中所有重复值的列表!
def findCommon(data):
flipped = {}
out = []
for i in data:
for value in data[i]:
if value not in flipped:
flipped[value] = [i]
else:
flipped[value].append(i)
for i in flipped:
if len(flipped[i]) > 1:
out.append(i)
return out
为了多样化,你也可以使用reduce()
:
>>> D = {'A': {1, 2, 3}, 'B': {2 ,4, 5}, 'C': {1, 2, 7}}
>>> reduce(lambda x, y: x & y, D.values()) # or use operator.and_ instead of lambda
{2}
reduce()
is a built-in function in Python 2.x, but needs to be imported from the functools
模块在 Python 3.x.
如果您使用 reduce
,最有效的方法是使用 operator.and_
from functools import reduce
from operator import and_
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
print(reduce(and_, D.values()))
但是set.intersection
将很难被击败:
In [89]: from functools import reduce
In [90]: from operator import and_
In [91]: timeit reduce(lambda x, y: x & y, D.values())
1000 loops, best of 3: 221 µs per loop
In [92]: timeit reduce(and_,D. values())
10000 loops, best of 3: 170 µs per loop
In [93]: timeit set.intersection(*D.values())
10000 loops, best of 3: 155 µs per loop