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.
>>> [list(line) for line in f]
[['j', 'd', 's', 's'], ['s', 'd', 'j', 'k'], ['n', 'b', 'j', 's']]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With