[英]Type of variable changes based on access?
I have a directed graph structure consisting of nodes and edges both of which subclass an Event parent class. 我有一个由节点和边组成的有向图结构,它们的两个子类都是事件父类。 Depending on external events, edges can either be active or inactive. 根据外部事件,边缘可以是活动的或不活动的。 I then find all the directed paths from a given node to the root node, but I really only care about the nodes along the way, not the edges. 然后,我找到了从给定节点到根节点的所有定向路径,但是我实际上只关心沿途的节点,而不关心边缘。 For instance, to convert from a set of edges to a set of nodes I use: 例如,要从一组边转换为一组节点,请使用:
>>> paths
[[<Edge F>, <Edge B>]]
>>> lst = [set(map(lambda e: e.tail, path)) for path in paths]
where path is a list of edges. 其中path是边的列表。 This is what confuses me: when I go to check the contents of lst
, it changes depending on how I access it 这就是让我感到困惑的地方:当我检查lst
的内容时,它会根据我访问它的方式而变化
>>> lst
[set([<Node 2>, <Node 1>])]
>>> [type(n) for n in path for path in lst]
[<class 'libs.network.Edge'>, <class 'libs.network.Edge'>]
>>> [type(n) for n in lst[0]]
[<class 'libs.network.Node'>, <class 'libs.network.Node'>]
Why aren't these two ways of accessing the type information the same? 为什么这两种访问类型信息的方式都不相同?
You have your list comprehension order wrong. 您的清单理解顺序有误。 Nested loops are listed from left to right . 嵌套循环从左至右列出。
So the expression 所以表达
[type(n) for n in path for path in lst]
is executed as 被执行为
for n in path:
for path in lst:
type(n)
so n
is taken from some random pre-assigned path
variable you had before, and it is that variable that contains Edge
instances. 因此n
取自您之前拥有的某个随机预先分配的path
变量,而该变量包含Edge
实例。 Those objects have nothing to do with the contents of lst[0]
you loop over in your other expression. 这些对象与您在其他表达式中循环播放的lst[0]
的内容无关 。
You probably wanted to do this the other way around: 您可能想以其他方式执行此操作:
[type(n) for path in lst for n in path]
so that path
is actually set from lst
before you iterate over it. 因此该path
实际上是在迭代之前从lst
开始设置的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.