如何使用Python中的行和列数据从文本文件中读取值

2024-10-05 17:39:38 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,这里基本上我有一个文本文件,包含许多行和列的数值数据可以看到下面的例子。在

21,73,12,73,82,10
17,28,19,21,39,11
17,39,19,21,3,91
12,73,17,32,18,31
31,29,31,92,12,32
28,31,83,21,93,20

我希望能够做的是分别读取每个值,同时也标识行和列号。 即第0行第2列为12

然后才能将行、列和值写入变量。ie=i,j,d

我可以把它们读入数组并按行拆分,得到列数和行数,我只是不知道如何将每个值分开。在

下面是一些我认为是用伪代码编写的代码,其中“I”和“j”是行和列号,“b”是上表中与此相关的数据,然后循环。在

^{pr2}$

Tags: 数据代码数组标识ie例子行和列文本文件
1条回答
网友
1楼 · 发布于 2024-10-05 17:39:38

这应该是基于您的原始代码实现的。在

# using with is the safest way to open files
with open(file_name, "r") as file:
    # enumerate allows you to iterate through the list with an index and an object
    for row_index, row in enumerate(file):
        # split allows you to break a string apart with a string key
        for col_index, value in enumerate(row.split(",")):
            #convert value from string to int
            # strip removes spaces newlines and other pesky characters
            b = int(value.strip())
            if b != 0:
                g.add_edge(row_index,col_index, b)

如果你想把它变成一个数组,你可以用列表理解来压缩它。在

^{pr2}$

相关问题 更多 >