目前,我正在这样做:
nodes = set([relation.source for relation in relations] +
[relation.target for relation in relations])
当然,肯定有一种更简单的方法,但是我找不到。
就像是
nodes = set([(relation.source, relation.target) for relation in relations])
但是这当然行不通。
谢谢
[编辑]
忘了提:
关系是字典,或者在我的情况下是对象的集合。
最佳答案
您可以在* -comprehension(列表,集合,字典,生成器表达式)中使用多个for
子句:
nodes = {
x
for relation in relations
for x in [relation.source, relation.target]
}
上面的表达式类似于:
nodes = set()
for relation in relations:
for x in [relation.source, relation.target]:
nodes.add(x)
nodes
使用生成函数的替代方法:
def source_targets(relations):
for relation in relations:
yield relation.source
yield relation.target
nodes = set(source_targets(relations))
关于python - 理解-从字典字段中列出 list ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25871652/