python reduce找到集合的并集 [英] python reduce to find the union of sets
问题描述
我正在尝试找到集合的并集.具体来说,我希望对networkx
图的字典中称为periodic_gs
的每个键的节点列表进行并集.我想使用reduce
函数,因为采用所有periodic_gs[x].nodes()
的并集似乎是合理的,其中x
是periodic_gs
的键.
I am trying to find the union of set of sets. Specifically I want the union of the list of nodes for each key in the dictionary of networkx
graphs called periodic_gs
. I would like to use the reduce
function as it seems reasonable to take the union of all periodic_gs[x].nodes()
where x
is a key of periodic_gs
.
这是我的尝试:
reduce(lambda x,y: set(periodic_gs[x].nodes()).union(set(periodic_gs[y].nodes())), periodic_gs.keys(), {})
对我来说,这就是说将字典中每个图的节点并集.出于某种原因,python告诉我:TypeError: unhashable type: 'dict'
我看不到此TypeError
,因为periodic_gs.keys()
是键的列表(它们是字符串,但我看不出这有什么用),以及在替换时lambda函数的参数将起作用.
To me, this says take the union of the nodes across each graph in the dictionary. For some reason, python tells me: TypeError: unhashable type: 'dict'
I do not see this TypeError
, because periodic_gs.keys()
is a list of the keys (they are strings but I do not see how this would matter), and when substituted in for the arguments to the lambda function will work.
什么是导致类型错误的原因,我该如何解决?
What is causing the type error and how do I fix it?
推荐答案
You can use set.union
like this:
>>> lis = [{1, 2, 3, 4}, {3, 4, 5}, {7, 3, 6}]
>>> set().union(*lis)
set([1, 2, 3, 4, 5, 6, 7])
可以使用 reduce
进行此操作,但是不要:
>>> reduce(set.union, lis)
set([1, 2, 3, 4, 5, 6, 7])
因为此reduce
由于需要构建和丢弃所有中间集,因此需要花费二次时间:
because this reduce
takes quadratic time due to all the intermediate sets it builds and discards:
In [1]: from functools import reduce
In [2]: sets = [{x} for x in range(1000)]
In [3]: %timeit set().union(*sets)
40.9 µs ± 1.43 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [4]: %timeit reduce(set.union, sets)
4.09 ms ± 587 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
此测试用例的速度降低了100倍,而且很容易变得更糟.
That's a 100x slowdown on this test case, and it can easily be even worse.
对于您的代码,这应该做到:
For your code, this should do it:
set().union(*(x.nodes() for x in periodic_gs.values()))
这篇关于python reduce找到集合的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!