在PHP python等效的2维数组插入

时间:2013-10-07 18:14:44

标签: php python arrays list

我没有PHP的经验,我必须将PHP脚本转换为python。我无法理解代码中这些行究竟是做什么的:

$vars = array();
$vars['a'] = array();
$vars['b'] = array();
$vars['b'][] =  'text1';

最后一行代表什么?如果我在代码中添加以下行会发生什么?

$vars['b'][] =  'text2';

我很感激将此转换为python的帮助。 非常感谢,

3 个答案:

答案 0 :(得分:1)

如果您想将PHP代码段转换为python,那么您可以获得的最接近的

>>> var = {}
>>> var['a'] = {}
>>> var['b'] = {}
>>> var['b'][len(var['b'] )] = 'text1'
>>> var['b'][len(var['b'] )] = 'text2'
>>> var
{'a': {}, 'b': {0: 'text1', 1: 'text2'}}

另一种变体

>>> class array(dict):
    def __getitem__(self, key):
        return dict.__getitem__(self, key)
    def __setitem__(self, key, value):
        if key == slice(None, None, None):
            dict.__setitem__(self, self.__len__(), value)
        else:
            dict.__setitem__(self, key, value)


>>> var = array()
>>> var['a'] = array()
>>> var['b'] = array()
>>> var['b'][:] = 'text1'
>>> var['b'][:] = 'text2'
>>> var
{'a': {}, 'b': {0: 'text1', 1: 'text2'}}

答案 1 :(得分:0)

最后一行只是添加一个带有字符串text的条目,其中包含数组$vars['b']的数字(递增)键。

$vars['b']为空时,它以键0开头。(=> $vars['b'][0] === 'text'


这意味着您的数组将如下所示:

array(2) {
  ["a"]=>
  array(0) {
  }
  ["b"]=>
  array(2) {
    [0]=>
    string(5) "text1"
    [1]=>
    string(5) "text2"
  }
}

(对不起;在您提出问题的时候,没有最后一个短语我也很感谢将此转换为python的帮助。但是......我不知道python。)

答案 2 :(得分:0)

// http://www.trainweb.org/mccloudrails/History/boxcars_runaround.jpg![a train with box cars][1]
// imagine this like a train, and each boxcar on that train has a name on it
// this is like a list in python @see http://www.tutorialspoint.com/python/python_lists.htm
$vars = array();

// this is the name of the first box car, now this box car is ALSO a train with box cars, ie, a train within a boxcar of a train
$vars['a'] = array();

// same as above, but with a different box car 
$vars['b'] = array();

// @see http://stackoverflow.com/questions/252703/python-append-vs-extend
$vars['b'][] =  'text1';

// Q) what  does the last line stand for? And what would happen if I add the line below to the code? $vars['b'][] =  'text2';
// A) This would make the array look somewhat like this: 
//    [a => [/* empty sad box car in an empty sad box car */]] [b => ['text1', 'text2'] ]

这不完全准确,但是一个很好的开始。 http://www.youtube.com/watch?v=ufmzc2sDmhs