[Python] How do I take a string of numbers and convert into a 2D 9x9 list?

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    From a string of numbers, no separators, to 2D 9x9 list. I get stuck on getting the numbers from the string into a 2D 9x9 array/list. I'm working on a Sudoku solver just to learn Python better.

    numbers = '084030001560014000001586704420001070005309802900200043100078005006105407000490000'


    I tried:

    list1 = []
    for n in numbers:
    for i in range(0,9):
    for j in range(0,9):
    list1[j].append(n)


    This gives me a list index out of range error.

    Same with this:

    list1 = []
    for i in range(0,9):
    for j in range(0,9):
    for n in numbers:
    list1[j].append(n)


    I tried using a list comprehension, but I don't quite understand that well enough, and if I cannot get the for loops to work, then I probably won't get the comprehension to work.

    I have found examples of comprehensions, but like I said, I don't understand them enough for a 2D list.

    It seems like this should be really simple, lol!

    I see a lot of questions on strings of numbers that are already comma separated, but I have not seen one without commas, yet.

    Continue reading...

Compartilhe esta Página