简体   繁体   English

Python可变长度二维数组

[英]Python variable length 2d arrays

Today is my first day learning Python and have a question about 2-dimensional arrays. 今天是我学习Python的第一天,并对二维​​数组有疑问。 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? 是否有类似于Java中的arraylist的东西? Here's my code so you can see what I mean. 这是我的代码,因此您可以了解我的意思。 It's for day 3 of last year's Advent of Code. 这是去年代码问世的第3天。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM