Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create two dimensional list of characters from file?

I need some simple help. I have file with content like this:

jdss
sdjk
nbjs

So there is unknown numbers of lines and unknown numbers of characters in every line but all of lines is the same length. I want to get a two dimensional list

[['j','d','s','s'],
['s','d','j','k'],
['n','b','j','s']]

how to do it in the simplest way? What I tried:

list = [[]]
for line in f:
    whichLine = 0
    for ch in line:
        list [whichLine].append(ch)
    list.append([])
    whichLine += 1

But it doesn't work like I want.

like image 510
Piotr Wasilewicz Avatar asked Jan 25 '26 16:01

Piotr Wasilewicz


2 Answers

>>> [list(line) for line in f]
[['j', 'd', 's', 's'], ['s', 'd', 'j', 'k'], ['n', 'b', 'j', 's']]
like image 153
Stefan Pochmann Avatar answered Jan 27 '26 06:01

Stefan Pochmann


list comprehension works well here.

my_list = [[c for c in line] for line in f]

(note its usually not a good idea to overwrite the name list)

if you don't want the newline characters

my_list = [[c for c in line.strip()] for line in f]
like image 27
cmd Avatar answered Jan 27 '26 08:01

cmd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!