![](/img/trans.png)
[英]Reading values from a text file with different row and column size in python
[英]How to read values from text file, with row and column data in 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
然后能够将行,列和值写入变量。 即= 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
这应该根据您的原始代码完成。
# 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.