[英]Why does this line take so long to run?
I have the following code, which gets a graph and set of ids to exclude, and returns the ids of nodes that do not appear in the nodes to exclude list. 我有以下代码,该代码获取要排除的图形和一组ID,并返回未出现在要排除的节点列表中的节点的ID。
I have two versions of the code. 我有两个版本的代码。 One that gets two lists, and the other that gets one list.
一个得到两个列表,另一个得到一个列表。 I am using
itertools.chain
to combine the two lists. 我正在使用
itertools.chain
来合并两个列表。
from itertools import chain
def GrapMinusNodes(Graph,nodes_to_exclude1,nodes_to_exclude2):
return (item.GetId() for item in Graph.Nodes() if item.GetId() not in chain(nodes_to_exclude1,nodes_to_exclude2))
and I have this one: 我有这个:
def GrapMinusNodes(Graph,nodes_to_exclude1,nodes_to_exclude2):
return (item.GetId() for item in Graph.Nodes() if item.GetId() not in nodes_to_exclude1)
The first method runs 20% slower than the second one. 第一种方法的运行速度比第二种方法慢20%。 What is the reason for that?
是什么原因呢? Is there a way to make this code run faster?
有没有办法使此代码运行更快?
Why are you using chain
here? 为什么在这里使用
chain
? Checking membership is O(n)
for an iterable, and you have to recreate that iterable for each item you're checking. 检查成员资格是否为
O(n)
可迭代,并且您必须为要检查的每个项目重新创建该可迭代。 Instead, pre-create a set
and test membership using that: 相反,请预先创建一个
set
并测试成员资格:
exclude = set().union(nodes_to_exclude1, nodes_to_exclude2)
return (item.GetId() for item in Graph.Nodes() if item.GetId() not in exclude)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.