【问题标题】:How to read values from text file, with row and column data in Python如何从文本文件中读取值,在 Python 中使用行和列数据
【发布时间】:2014-04-25 14:37:21
【问题描述】:

您好,基本上我有一个文本文件,其中包含许多行和列的数值数据,下面是一个示例。

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

我想要做的是分别读取每个值,并同时识别行号和列号。 IE。第 0 行第 2 列将是 12

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

我可以将它们读入一个数组并按行分割,得到列数和行数,我只是不知道如何单独分隔每个值。

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

i = 0
for a in array:
    j = 0 
    for b in array:
        if b != 0:
            write.code(i,j,b)
        j+=1
    i+=1

【问题讨论】:

  • 学习 Python 的 CSV 模块。
  • 试试看:map(lambda l: map(int, l.split(',')), open('file')) 好玩
  • 尝试 'for b in a:' 而不是 'for b in array:'

标签: python csv text


【解决方案1】:

这应该根据您的原始代码来解决问题。

# 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)

如果你只想把它变成一个数组,你可以用列表推导来压缩它。

with open(file_name, "r") as file:
     my_array = [ [int(value.strip()) for value in row.split(",")] for row in file]

【讨论】:

  • 在单独的 .py 文件中进行测试时,我想做的事情很棒,但是,我遇到了一个我似乎无法解决的错误,如果它有助于 Traceback(大多数最近通话最后):文件“yes2.py”,第 65 行,在 g.add_edge(u,v,w) 文件“yes2.py”,第 27 行,在 add_edge self.adj[u].append(边缘)KeyError:0
  • 这是您自己的自定义功能中的一个问题,我无法帮助您。尝试将所有数据打印到 self.adj[u].append(edge) 并评估是否有问题
  • 错误还指出u 的值为0,并且self.adj 中没有使用该键的索引项
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
相关资源
最近更新 更多