Reputation: 35
So I have a text file that looks like this:
abcd
efghij
klm
and I need to convert it into a two-dimensional list. And it should look like this:
[['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h', 'i', 'j'],
['k', 'l', 'm']]
so far I have managed to get this result:
[["abcd"], ["efghij"], ["klm"]]
Can anyone help me figure out what the next step should be? Here is my code so far:
def readMaze(filename):
with open(filename) as textfile:
global mazeList
mazeList = [line.split() for line in textfile]
print mazeList
Upvotes: 0
Views: 1923
Reputation: 1506
As explained above, you just need to build a list from the strings.
Assuming the string is held in some_text;
lines = some_text.split('\n')
my_list = []
for line in lines:
line_split = list(line)
my_list.append(line_split)
as one-liner;
my_list = map(lambda item: list(item), some_text.split('\n'))
should do the trick.
Upvotes: 1
Reputation: 23743
Make a list of each line in the file:
with open('tmp.txt') as f:
z = [list(thing.strip()) for thing in f]
Upvotes: 2
Reputation: 54162
(apparently I'm misremembering, str.split()
splits on whitespace. str.split('')
splits each character separately.str.split('')
throws a ValueError
for "empty separator"
)
You'll just build a list
from it.
text = """abcd
efghij
klm"""
mazelist = [list(line) for line in text.splitlines()]
# the splitlines call just makes it work since it's a string not a file
print(mazelist)
# [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm']]
Upvotes: 4