简体   繁体   English

从文本文件获取输入并在Python中以2-D模式存储

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

Suppose I have the text file contents as: 假设我的文本文件内容为:

00   0.21 
11   0.12
10   2.51
01   0.25

Where the first column is binary and the second column is float value. 其中第一列为二进制,第二列为浮点值。 After reading to the text file my output should be in the following 2-d array format: 读取文本文件后,我的输出应为以下二维数组格式:

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

please give any idea to obtain this output. 请给出任何想法以获取此输出。

You can use split . 您可以使用split

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

Here an example using the proposed csv-module. 这里是使用建议的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)

Example output: 输出示例:

[['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]]

You said that you are reading in a text file. 您说您正在阅读一个文本文件。 It would appear that you are reading in a text line such as 看来您正在阅读诸如

inline = '00 0.21'

You would use split to get 您将使用split获得

inlst = inline.split(' ')

which produces 产生

['00', '0.21']

given 给定

input1 = []
input2 = []

You now use 您现在使用

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

This now adds the appropriate entries to your lists. 现在,这会将适当的条目添加到您的列表中。 Now just put this in the loop over your line reading logic. 现在,将其放在您的线路读取逻辑中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM