简体   繁体   中英

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 .

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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