簡體   English   中英

從文本文件獲取輸入並在Python中以2-D模式存儲

[英]Getting inputs from the text file and storing as 2-d pattern in python

假設我的文本文件內容為:

00   0.21 
11   0.12
10   2.51
01   0.25

其中第一列為二進制,第二列為浮點值。 讀取文本文件后,我的輸出應為以下二維數組格式:

input1 = [[0,0],[1,1],[1,0],[0,1]]
input2 = [[0.21],[0.12],[2.51],[0.25]]

請給出任何想法以獲取此輸出。

您可以使用split

for line in file:
    binColumn, floatColumn = line.split()
    input1.append(list(map(int, binColumn)))
    input2.append([float(floatColumn)])

這里是使用建議的csv模塊的示例。

import csv

with open ('egal', 'r') as f:
    #Filtering away empty items
    #If there is a neater way, please advice
    lines = [[x for x in x if x] for x in csv.reader(f, delimiter = ' ')]

print(lines)
input1, input2 = zip(*lines)
input1 = [[int(x) for x in x] for x in input1]
input2 = [[float(x)] for x in input2]
print(input1)
print(input2)

輸出示例:

[['00', '0.21'], ['11', '0.12'], ['10', '2.51'], ['01', '0.25']]
[[0, 0], [1, 1], [1, 0], [0, 1]]
[[0.21], [0.12], [2.51], [0.25]]

您說您正在閱讀一個文本文件。 看來您正在閱讀諸如

inline = '00 0.21'

您將使用split獲得

inlst = inline.split(' ')

產生

['00', '0.21']

給定

input1 = []
input2 = []

您現在使用

input1.append((inlst[0][0], inlst[0][1]))
input2.append(float(inlst[1]))

現在,這會將適當的條目添加到您的列表中。 現在,將其放在您的線路讀取邏輯中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM