繁体   English   中英

使用python从文本文件中打印出特定行

[英]Printing out a specific line from a text file using python

这是用于学校练习,也是我的新手,所以请多多包涵。 我有一个图“ fileName”和一个程序,在该程序下方输出一个邻接矩阵。 矩阵被放置在这样的列表中:

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

通过此邻接矩阵,它列出了理论上的体育比赛,其中互相对抗的球队被列为“ 1”,而没有比赛的球队被列为“ 0”。 我还有另一个文件“ fileName2”,其中列出了一堆团队名称,其中文本文件的每一行都有一个团队名称。 我的目标是打印出彼此之间没有参加比赛的球队的名称。 到目前为止,我的代码可以在下面找到(它有很多调试工件,我知道这很杂乱):

vertices = int(input('How many vertices are there in the graph?'))
fileName = input("What's the name of the file of graph to read?")
fileName2 = input("What's the name of the file of team names to read?")

f1 = open(fileName, 'r')
f2 = open(fileName2, 'r')

# Create adjacency matrix skeleton for storing later

adjMatrix = [ [0] * vertices for i in range(vertices) ]
# adjMatrix = [[0] * vertices] * vertices

# Looping through the file to obtain the connecting vertices

for line in f1:
    line = line.replace('\n', '')
    line = line.split(' ')
    i = 0
    for vert in line:
        line[i] = int(vert)
        i += 1

    j = line[0]
    k = line[1]

    adjMatrix[j][k] = 1
    adjMatrix[k][j] = 1

print(adjMatrix)

# Print out the teams who have yet to play against each other

for m in range(vertices):
    # print(adjMatrix[m])
    for n in range(vertices):
        # print(adjMatrix[m][n])
        if m != n and adjMatrix[m][n] == 0:
            if m < n:
                print(m,n)
                t = 0
                for team in f2:
                    if m == t:
                        print(team)
                    if n == t:
                        print(team)
                    t += 1
            # Is this elif statement necessary as we sort through the teams?
            elif m > n:
                print(n,m)

# for team in f2:
#   print(team)

f1.close()
f2.close()

到目前为止,此代码的问题在于,当从“ if m <n”语句中调用该代码行时,“ for team in f2”循环不会再次循环。 因此,它只打印出尚未打过的一场比赛,而不打印出另一场没有打过的比赛。

应该有2个尚未比赛的比赛(0-3和2-3),因此它将打印0-3而不是2-3列出的名称。

想知道如何:1.解决文件'f2'的for循环问题; 和2.改进到目前为止我拼凑的这段代码。

提前致谢。

注意:我使用的是Python 3.5.3

当您遍历文件f2一次时,必须倒带该文件才能再次启动:

f2.seek(0)

暂无
暂无

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

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