简体   繁体   中英

Convert a string into a two-dimensional array in Python

So I was trying to do a maze and wanted to transform the maze into a two-dimensional array so it would be easier to manipulate, but I didn't really succeed. The best I've done is a list of string with the following:

map = """
OOOOOOOOOO
O O    O O
O . OO   O
O O O   XO
O OOOO O.O
O O O    U
O OOOOOO.O
O O      O
O O OOOOOO
O . O    O
OOOOOOOOOO
"""
map = [i for i in map.splitlines()]

Thanks for the help

splitlines() returns a list of strings. Each string being a line.

So when you call it on your example, it returns a list of strings. If you want a list of lists, you must convert each string to a list. This can be done easily with the list() function:

map = [list(line) for line in map.splitlines()]

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