2016-02-27 116 views
0

我有一個簡單的數組,我正在存儲字符串。將現有數組轉換爲多維

例如,

item['name'] = 'suchy' 
item['score'] = 'such' 

現在,然後,在遊戲後期,我想添加一個數組到這個項目。

在我的情況下,不是項目[]已經是一個數組,'名稱'和'分數'是他們的鑰匙?我將變量存儲爲'such'和'suchy',但我不想存儲字符串,而是希望存儲更多的數組。

我略高於愚蠢,但這對我來說似乎很複雜。 Python如何處理?

編輯:

道歉急促。

在PHP中,你可以這樣做

$myArray = array 
{ 
    'suchy' => 'such', 
    'anotherarray' => array { 'something', 'else'} 
} 

後來它很容易的東西添加到陣列中。

$myArray[0][3] = 'etc' 

我想解決如何做類似的蟒蛇。感謝迄今爲止的評論。已經學到了一些東西。謝謝!

+3

你能給出一個期望輸出的例子嗎?順便說一句,你提到的數組,但你的例子是一本字典。 – idjaw

+1

你也可以展示你的代碼嘗試你正在努力實現的目標嗎? – idjaw

+1

你可以簡單地定義一個'outerList = []',然後當你完成你的字典'item'時,你只需要'outerList.append(item)' – Obsidian

回答

1

在Python中,這樣的:

$myArray = array 
{ 
    'suchy' => 'such', 
    'anotherarray' => array { 'something', 'else'} 
} 

是這樣的:

my_dict = { 
    'suchy': 'such', 
    'anotherarray': ['something', 'else'] 
} 

如果你想在第一級添加的東西,它只是:

my_dict['stuff'] = [1,2,3,4] 

現在將使它:

my_dict = { 
    'suchy': 'such', 
    'anotherarray': ['something', 'else'] 
    'stuff': [1, 2, 3, 4] 
} 

如果你想要更新列表,假設存儲在 'anotherarray' 列表中,你這樣做:

輸出的 my_dict['anotherarray']

['something', 'else', 'things'] 

my_dict['anotherarray'].append('things') 

我建議在dictionaries閱讀教程在Python:

Documentation from official docs

1

如果我理解你正確,你需要這樣的

item = {} 
item['somekey'] = ['suchy'] # you're indicate that in dictionary item you will store list so in this lit you can put anything you want later and list too 
item['score'] = ['such'] 

不是以後在你的遊戲中,你可以使用它像這樣

item['somekey'].append([1,11,2,3,4]) 

,或者如果你想在你的字典添加新項目值等於數組 你可以寫這個

item['newkey'] = [1,2,3,4] 
+0

謝謝,我更新了這篇文章。我會嘗試你所說的 – willdanceforfun