سؤال

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
هل كانت مفيدة؟

المحلول 2

Make a list of each line in the file:

with open('tmp.txt') as f:
    z = [list(thing.strip()) for thing in f]

نصائح أخرى

str.split() splits on whitespace. str.split('') splits each character separately. (apparently I'm misremembering, 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']]

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top