简体   繁体   English

如何获取元组列表中的元素

[英]How to get elements of a list of tuples

I have a set of nodes 我有一组节点

nodes = ["uno","dos","tres","cuatro","cinco","seis"]

and a set of edges 和一组边缘

edges = [("uno", "dos"),
     ("uno", "tres"), 
     ("dos", "tres"), 
     ("dos", "cuatro"), 
     ("tres", "cuatro"), 
     ("tres", "cinco"), 
     ("cuatro", "cinco"), 
     ("cuatro", "seis"), 
     ("cinco", "seis")]

I have defined the inverse of these edges 我已经定义了这些边的反面

inverses =[(j,i) for (i,j) in edges]

And now I have my set of arcs 现在我有了一套

arcs = edges + inverses

My problem is that I want to get all the elements in the set of arcs which have a determined first element. 我的问题是我想获得一组确定的第一个元素的弧集中的所有元素。 That is 那是

ArcsOut[i in nodes] = [(i,j) for (i,j) in arcs for i in nodes for j in nodes].

I want to obtain something like this. 我想获得这样的东西。 If I order to get all arcs that have their fist component "uno", I would like to have: 如果我要获得所有具有拳头成分“ uno”的弧,我希望拥有:

ArcsOut["uno"]= [("uno", "dos"),("uno", "tres"),("dos", "uno"),("tres", "uno")] 

But I do not know how I can order that. 但是我不知道该如何订购。 Thanks in advance! 提前致谢!

Use the following syntax to create a dictionary: 使用以下语法创建字典:

ArcsOut = dict(((i,[(k,l) for k,l in arcs if k == i]) for (i,j) in arcs))

Then ArcsOut['unos'] = desired output. 然后ArcsOut ['unos'] =所需的输出。

/* EDIT */ / *编辑* /

Performancewise consider using a defaultdict : 在性能方面考虑使用defaultdict

ArcsOut = defaultdict(list)
for k, v in arcs:
    ArcsOut[k].append((k,v)) 

You can do this with a list comprehension. 您可以通过列表理解来做到这一点。 The nice part is you can use the tuple unpacking together with the condition to make it very short and to the point, at the same time readable. 令人高兴的是,您可以将元组解包与条件一起使用,以使其非常简短,并达到目的,同时可读性强。

arc_out = {node: [(i, j) for i, j in arcs if i == node] for node in nodes]

Instead, if you want to get all edges where either i or j matches a specific node name, you can do this 相反,如果你想获得在选择了所有的边缘i还是j特定节点名称相匹配,你可以这样做

[edge for edge in arcs if 'uno' in edge]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM