2016-02-27 199 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