![](/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.