为什么循环在一次迭代中表现不同?

时间:2016-12-08 11:00:58

标签: python python-2.7

我有这段代码:

gs = open("graph.txt", "r")

gp = gs.readline()
gp_splitIndex = gp.find(" ")
gp_nodeCount = int(gp[0:gp_splitIndex])
gp_edgeCount = int(gp[gp_splitIndex+1:-1])

matrix = [] # predecare the array
for i in range(0, gp_nodeCount):
    matrix.append([])
    for y in range(0, gp_nodeCount):
        matrix[i].append(0)

for i in range(0, gp_edgeCount-1):
    gp = gs.readline()
    gp_splitIndex = gp.find(" ") # get the index of space, dividing the 2 numbers on a row
    gp_from = int(gp[0:gp_splitIndex])
    gp_to = int(gp[gp_splitIndex+1:-1])
    matrix[gp_from][gp_to] = 1

print matrix

文件graph.txt包含:

5 10
0 1
1 2
2 3
3 4
4 0
0 3
3 1
1 4
4 2
2 0

前两个数字告诉我,GRAPH有5个节点和10个边。以下数字对演示了节点之间的边缘。例如,“1 4”表示节点1和4之间的边缘。

问题是,输出应该是这样的:

[[0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [1, 0, 0, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]]

但不是那样,我明白了:

[[0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]]

只有一个数字不同,我无法理解为什么会发生这种情况。边缘“3 1”不存在。有人可以解释一下,问题在哪里?

4 个答案:

答案 0 :(得分:5)

for i in range(0, gp_edgeCount-1):更改为

for i in range(0, gp_edgeCount):

range()函数已执行“-1”操作。 range(0,3) "==" [0,1,2]

缺少“3 1”边缘,缺少“2 0”边缘,这是最后一个边缘。矩阵从0开始计数。

答案 1 :(得分:3)

马蒂亚斯拥有它;您不需要edgeCount - 1,因为range函数不包含迭代中的结束值。

您可以采取其他一些措施来清理代码:

  • with运算符是打开文件的首选,因为它会自动关闭它们
  • 您不需要致电find并手动切片,split已经做了您想做的事。
  • 您可以使用生成器表达式和可迭代解包直接转换并分配给一对数字
  • 您只需使用结束值调用range0开头就是隐含的。
  • 乘法运算符可用于初始化列表

所有这些变化:

with open('graph.txt', 'r') as graph:
    node_count, edge_count = (int(n) for n in graph.readline().split())
    matrix = [[0]*node_count for _ in range(node_count)]
    for i in range(edge_count):
        src, dst = (int(n) for n in graph.readline().split())
        matrix[src][dst] = 1

print matrix
# [[0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [1, 0, 0, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]]

答案 2 :(得分:2)

只是为了保留你的代码和风格,当然它可以更具可读性:

gs = open("graph.txt", "r")
gp = gs.readline()

gp_splitIndex = gp.split(" ")
gp_nodeCount = int(gp_splitIndex[0])
gp_edgeCount = int(gp_splitIndex[1])
matrix = [] # predecare the array
for i in range(0, gp_nodeCount):
    matrix.append([])
    for y in range(0, gp_nodeCount):
        matrix[i].append(0)


for i in range(0, gp_edgeCount):
    gp = gs.readline()
    gp_Index = gp.split(" ") # get the index of space, dividing the 2 numbers on a row
    gp_from = int(gp_Index[0])
    gp_to = int(gp_Index[1])
    matrix[gp_from][gp_to] = 1

print matrix

确切地说是最后一个未使用的实例..来自您文件的2 0。因此错过了1.祝你有愉快的一天!

答案 3 :(得分:1)

其他答案是正确的,另一个版本类似于tzaman:

with open('graph.txt', mode='r') as txt_file:
    lines = [l.strip() for l in txt_file.readlines()]

number_pairs = [[int(n) for n in line.split(' ')] for line in lines]

header = number_pairs[0]
edge_pairs = number_pairs[1:]

num_nodes, num_edges = header
edges = [[0] * num_nodes for _ in xrange(num_nodes)]
for edge_start, edge_end in edge_pairs:
    edges[edge_start][edge_end] = 1

print edges