簡體   English   中英

Python可變長度二維數組

[英]Python variable length 2d arrays

今天是我學習Python的第一天,並對二維​​數組有疑問。 我需要創建一個二維數組,但不知道每個數組的大小。 是否有類似於Java中的arraylist的東西? 這是我的代碼,因此您可以了解我的意思。 這是去年代碼問世的第3天。 因此,如果您還沒有完成並想了解我正在考慮的設置方式,我想會稍有麻煩。

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

謝謝你的幫助。

我相信你想要這樣的東西

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