简体   繁体   中英

How to split strings (in nested lists) every character?

Reading a text maze from a file, consists of a large series of walls (#) and openings ( ).

The maze needs to be read into a 2-dimensional array.

I can't figure out how to split each '#' and ' ' so that they are separate.

Just calling list() should split each character individually as an element in a list

from pprint import pprint as pp

def loadMaze(mazeName):
    global grandList
    grandList = []
    with open(mazeName) as sourceList:
        for line in sourceList:
            eachList = list(line)
            grandList.append(eachList)
        pp(grandList)

Don't call .split() .

eachList = list(line.strip('\n'))

because string.split() is for separating a string by whitespace, into a list of sub-strings:

>>> "a bb ccc".split()
['a', 'bb', 'ccc']

or separating by a character:

>>> "a/bb/ccc".split('/')
['a', 'bb', 'ccc']

list(some_string) will make a list of the characters in the string:

>>> list("a, bb, ccc")
['a', ',', ' ', 'b', 'b', ',', ' ', 'c', 'c', 'c']

Yeap! You almost made it, just don't split the strings.

You can do it the easy way,

with open(mazeName) as sourceList:
    for line in sourceList:
        grandList.append(list(line))
    pp(grandList)

or your own way:

with open(mazeName) as sourceList:
    for line in sourceList:
        grandList.append([c for c in line])
    pp(grandList)

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