如何在python中获取文件每行的第一个数字?

mnemlml8  于 2022-12-01  发布在  Python
关注(0)|答案(1)|浏览(234)
inputFile = open(filename, "r")

with open(filename) as f:
    content = f.readlines()
li = [x.strip() for x in content]
print(li)

输出量:

['4', '0 1 2 3', '1 0 2 3', '2 0 1 3', '3 0 1 2']

预期输出:

The number of total vertices is 4
Vertex 0: (0, 1) (0, 2) (0, 3)
Vertex 1: (1, 0) (1, 2) (1, 3)
Vertex 2: (2, 0) (2, 1) (2, 3)
Vertex 3: (3, 0) (3, 1) (3, 2)

我知道如何将元素转换为整数,但每行都不相同,txt文件的格式如下:

4
0 1 2 3
1 0 2 3
2 0 1 3
3 0 1 2

是否需要用.split()方法分隔?

yxyvkwin

yxyvkwin1#

试试看:

with open("your_file.txt", "r") as f:
    total_vertices = int(next(f))

    vertices = []
    for _ in range(total_vertices):
        row = list(map(int, next(f).split()))
        vertices.append([(row[0], v) for v in row[1:]])

print("The number of total vertices is", total_vertices)
for i, v in enumerate(vertices):
    print(f"Vertex {i}:", *v)

印刷品:

The number of total vertices is 4
Vertex 0: (0, 1) (0, 2) (0, 3)
Vertex 1: (1, 0) (1, 2) (1, 3)
Vertex 2: (2, 0) (2, 1) (2, 3)
Vertex 3: (3, 0) (3, 1) (3, 2)

相关问题