用python获取列表
因此,我试图编写一个定义来读取节点和边。这是我的代码,但它似乎不起作用用python获取列表,python,list,edges,Python,List,Edges,因此,我试图编写一个定义来读取节点和边。这是我的代码,但它似乎不起作用 #ideal nodes list should be ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'] 我可以帮你 试试这个: """ read nodes""" def rd_nodes(a): nline =[line.split(":")[1].replace(';',',').split(',') for line in a] fo
#ideal nodes list should be
['A','B','C','D','E','F','G','H','I','J','K','L','M','N']
我可以帮你
试试这个:
""" read nodes"""
def rd_nodes(a):
nline =[line.split(":")[1].replace(';',',').split(',') for line in a]
for i in nline:
return i
如果需要,可以使用
节点
和边
的结构来维护顺序。只需使用节点和边作为dict键,然后在脚本末尾获得键列表。因为@skovorodkin有正确的答案,但是如果您想要纯Python版本(尽管我不知道为什么),您可以使用此代码
from itertools import combinations
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
nodes = set()
edges = set()
for line in s.split():
clusters = line.split(':')[1].split(';')
for cluster in clusters:
_nodes = cluster.split(',')
nodes.update(_nodes)
edges.update(combinations(_nodes, 2))
s=”“”
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def组合(节点):
如果len(节点)<2:
返回(元组(节点))
其他:
i=1
ret_tuple=[]
对于n个in节点:
rest=节点[i:]
对于静止的r:
ret_tuple.append(tuple([n,r]))
i+=1
返回元组(ret_元组)
节点=集合()
边=集()
对于s.split()中的行:
clusters=line.split(“:”)[1]。split(“;”)
对于集群中的集群:
_nodes=cluster.split(',')
nodes.update(_节点)
edges.update(组合(_节点))
打印节点
打印边缘
我认为您应该在rd_节点中使用yield
而不是return
,graph
@PatrickHaugh的数据结构,yield和return似乎具有相同的功能。但是当我尝试时,它仍然不会得到正确的结果。@PatrickHaugh图形应该是带有元组的列表。检查上面的数据集。它是否有任何方式像我们不导入任何包,并使用for循环编写定义以获取节点和边?当然,只需检查我在文章中提供的指向组合函数doc的链接,它有一个纯Python版本。
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def combinations(nodes):
if len(nodes) < 2:
return (tuple(nodes))
else:
i = 1
ret_tuple = []
for n in nodes:
rest = nodes[i:]
for r in rest:
ret_tuple.append(tuple([n,r]))
i += 1
return tuple(ret_tuple)
nodes = set()
edges = set()
for line in s.split():
clusters = line.split(':')[1].split(';')
for cluster in clusters:
_nodes = cluster.split(',')
nodes.update(_nodes)
edges.update(combinations(_nodes))
print nodes
print edges