2013-10-07 66 views
2

我幾乎沒有PHP的經驗,我必須將php腳本轉換爲python。我不明白這些行在代碼中的確切含義:2維數組插入php python等效

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

最後一行代表什麼?如果我將下面的代碼添加到代碼中會發生什麼?

​​

我將不勝感激幫助也轉換成python。 非常感謝,

回答

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'}} 
+0

我用append代替len(var ['b'])。我想它的工作方式與 – googiddygoo

+0

@googiddygoo:如果你使用'dict',append方法可能不可用。嚴格來說,PHP的數組是關聯數組,最好被翻譯成pythons字典 – Abhijit

+0

是的,我使用的是列表而不是字典。但改爲代詞。完美的作品。謝謝 – googiddygoo

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。)

+0

按下輸入這麼快,當張貼抱歉。謝謝 – googiddygoo

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