0

I am trying to create a maze using list of lists, where each line of a maze is a separate element of a list. This list has numbers 0 or 1 which determine the wall/path in the maze as well as the start ("S") and end ("E"). But when I append each individual number to the list it's all appearing in quotation marks. The letters in quotations is fine but I want the numbers to be added without the quotations. Is there a way to do this?

This is my code for appending to the list:

if maze != "invalid":
        row = maze.split(",")
        for line in row:
          col = []
          for element in range(0, len(line)):
            col.append(line[element])

      mazelist.append(col)
    transformed_maze_validation.append(mazelist)

This is the output I get:

enter image description here

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Hamza Asim
  • 39
  • 6
  • You can ensure the int casting like this : `col.append(int(line[element]))` But check beforehand that `line[element].isalpha()` is `False` – rafidini Dec 09 '22 at 09:11
  • 1
    Do you plan to do math with the numbers? If they only signify which sides have walls, why not just keep them as strings? You might not even have to convert the lines to lists, since you can index into strings as well, i.e. just `mazelist = maze.split(",")` – tobias_k Dec 09 '22 at 09:22
  • Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) – mkrieger1 Dec 09 '22 at 09:22

1 Answers1

1

Here is a snippet that shows how you can make sure that everything that can be converted to int is converted.

items = ['1','2','S','E']
results = []

for item in items:
    try:
        item = int(item)
    except ValueError:
        pass
    results.append(item)

Result in [1, 2, 'S', 'E']

Aidis
  • 1,272
  • 4
  • 14
  • 31