-1

所以我一直试图让这两个函数工作,当我单独执行它们时,它们工作,但是当我使用 elif 函数组合这两个函数时,它只运行第一个函数并打印出位置列表,并且错误说“ neighbour_list 未定义”

这是我的代码

 my_file=open("test_graph_1.txt","r")
 x=[]
 y=[]
 nodenumber=[]
 positionx=[]
 positiony=[]


for row in my_file:

    value=row[:-1]

    my_list=value.split(",")

    if len(my_list)==3:
        nodenumber.append(int(my_list[0]))

        positionx.append(int(my_list[1]))
        positiony.append(int(my_list[2]))

        nodenumber1 =[(nodenumber[a],positionx[a],positiony[a]) for a i range(len(nodenumber))]
        position_list=tuple(nodenumber1)




    elif len(my_list)==2:
        x.append(int(my_list[0]))
        y.append(int(my_list[1]))

        l1 = [(x[i] , y[i]) for i in range(len(x))]
        l2 = [(y[i] , x[i]) for i in range(len(x))]
        l1.extend(l2)
        neighbour_list=[[l[0] for l in l1 if l[1] == j] for j in range(len(x))]


 print("position_list",position_list)
 print("neigh",neighbour_list)

但是当我打印代码时,位置列表会很好,但是 neighbour_list 会像这样出现:[[4, 1], [0, 4, 2], [1, 3], [2, 5, 4], [ 3, 0, 1], [3], []] 额外的空字符串,它不应该存在,但在那之前一切都很好

4

1 回答 1

0

If, for each pass through the loop, my_list[2] != "" is True, then neighbour_list is never defined. Then

print("neigh",neighbour_list)

would raise a NameError: the neighbour_list is not defined.


Instead, define neighbour_list before entering the for-loop. You could also use

if len(my_list) == 3:
    ...
elif len(my_list) == 2:
    ...
else:
    ...

to handle the two types of lines you expect to receive.


N = 5
position_list = list()
neighbour_list = [list() for j in range(N)]

with open("test_graph_1.txt","r") as my_file:
    for row in my_file:
        try:
            my_list = map(int, row.split(','))
        except ValueError:
            # Choose how to handle malformed lines
            print('invalid line: {!r}'format(row))
            continue
        if len(my_list) == 3:
            nodenumber, positionX, positionY = my_list
            position_list.append(tuple([nodenumber,positionX,positionY]))
        elif len(my_list) == 2:
            nodenumber1, nodenumber2 = my_list
            neighbour_list[nodenumber1].append(nodenumber2)
            neighbour_list[nodenumber2].append(nodenumber1)            
        else:
            # Choose how to handle lines with more than 3 or less than 2 items
            continue

print(position_list)
print("neigh", neighbour_list)

You might also want to use a graph library like networkx or igraph.

于 2014-09-28T13:19:43.603 回答