简体   繁体   中英

How can I convert strings from a text file into matrix (python)

For example: content of myfile has

    fsdfasf
    frjfmcd
    39djaxs

I want to convert this in to a matrix where it consists of my_matrix=[['f','s','d','f','a','s','f'],['f','r','j'......]]

I've tried reading the file using

for line in file:
        line = line.strip('\n)
        print(line)

But it's not giving me the desired output.

What am I missing to do?

You need to turn your string into a list to get the output you want. Since strings are sequences, when you pass a string to list() if breaks it up into individual characters:

with open(path) as file:
    matrix = [list(line.strip()) for line in file]
    

matrix:

[['f', 's', 'd', 'f', 'a', 's', 'f'],
 ['f', 'r', 'j', 'f', 'm', 'c', 'd'],
 ['3', '9', 'd', 'j', 'a', 'x', 's']]

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