[英]comprehension - make a list out of a dictionary fields
目前,我正在這樣做:
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))
您可以使用itertools.chain.from_iterable
,這可能比設置的理解要好一些:
from itertools import chain
nodes = set(chain.from_iterable((r.source, r.target) for r in relations))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.