简体   繁体   中英

Python variable length 2d arrays

Today is my first day learning Python and have a question about 2-dimensional arrays. I need to create a 2 dimensional array but don't know the size of each of them. Is there something similar to the arraylist like in Java? Here's my code so you can see what I mean. It's for day 3 of last year's Advent of Code. So I guess a slight spoiler ahead if you haven't done it and want to see the way I'm thinking of setting it up.

f=open('directions.txt')
houses = [0][0]
rows = 0
column = 0
total = 0
for line in f:
    for c in line:
         if (str(c) == '^'):
        rows += 1
        houses[rows][column] += 1
    elif (str(c) == '>'):
        column += 1
        houses[rows][column] +=1
    elif (str(c)=='<'):
        column -= 1
        houses[rows][column-=1] +=1
    else:
        rows -= 1
        houses[rows][column] +=1

Thanks for any help.

I believe you want something like this

houses = dict()
rows = 0
column = 0
total = 0
for line in f:
    for c in line:
        houses.setdefault(rows,dict())
        houses[rows].setdefault(column, 0)
        if (str(c) == '^'):
            houses[rows][column] += 1
            rows += 1
        elif (str(c) == '>'):
            houses[rows][column] +=1
            column += 1
        elif (str(c)=='<'):
            houses[rows][column] +=1
            column -= 1
        else:
            houses[rows][column] +=1
            rows -= 1

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