我在 PHP 方面的经验很少,我必须将 php 脚本转换为 python。我无法理解这些行在代码中到底做了什么:
$vars = array();
$vars['a'] = array();
$vars['b'] = array();
$vars['b'][] = 'text1';
最后一行代表什么?如果我将下面的行添加到代码中会发生什么?
$vars['b'][] = 'text2';
我也将不胜感激将其转换为 python 的帮助。非常感谢,
如果您想将 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'}}
最后一行只是将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。)
// 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