2013-03-07 127 views
0

我想要一個具有映射的python分層數據結構,並且該值將是一個元組。在某些情況下,元組的長度爲1.每當元組的長度爲1時,Python智能地平整結構。觀察下面的示例,它可以在Python解釋器中運行。在「另一個場景」中,我預計這個長度是1,但是它已經鑽了一層,並且有了基本的步驟。這完全搞砸了我的測試,因爲我依靠它作爲一個具有命令,函數列表,函數列表的元組。Python扁平化我的元組結構

問題 - 爲什麼會發生這種情況?我如何讓python不要將它弄平?

import os 

def run(): 
    my_scenario = { 
      "scenario_name" : 
      ( # Each scenario is a List of (command, function_list, function_list) 
       # function_list = one function OR tuple of functions 
       (
        "command1", 
        (
         os.path, 
         os.path.exists 
        ), 
        None 
       ), 
       (
        "command2", 
        (
         os.path, 
         os.path.exists 
        ), 
        None 
       ) 
      ) 
     } 
    another_scenario = { 
      "scenario_name" : 
      (
       (
        "command1", 
        (
         os.path, 
         os.path.exists 
        ), 
        None 
       ) 
      ) 
    } 
    for name in my_scenario: 
     print "Full Scenario is %s" % str(my_scenario[name]) 
     print "Length should be 2 -> %s" % len(my_scenario[name]) 
    for name in another_scenario: 
     print "Full Scenario is %s" % str(another_scenario[name]) 
     print "Length should be 1 -> %s" % len(another_scenario[name]) #Prints 3 as it drills one level down 


if __name__ == "__main__": 
    run()  
+0

如果我更換()用[]即,使用左旋在上面的元組ist insted我得到我期望的輸出。我不想使用列表,雖然 – 2013-03-07 10:09:26

回答

2

您需要添加一個逗號:

another_scenario = { 
     "scenario_name": 
     (
      (
       "command1", 
       (
        os.path, 
        os.path.exists 
       ), 
       None 
      ), # <- Note this comma 
     ) 
} 

,使一個元組,否則它只是一種表達。

>>> (1) 
1 
>>> (1,) 
(1,) 
>>> type((1)) 
<type 'int'> 
>>> type((1,)) 
<type 'tuple'> 

事實上,它是逗號定義的元組,而不是括號::

>>> 1, 
(1,) 
>>> 1, 2 
(1, 2) 

的括號是1-元件的元組只能通過逗號的存在從表達式區分只有當你需要定義一個元組需要:

>>>() 
() 
+0

啊,我應該抓住這一點。不幸的是,這使得DSL不友好(雖然我同意這背後的原因)。我不能指望我的情景專家記得添加尾隨的「,」。我現在將切換到使用[]列表語法,看起來好一點 – 2013-03-07 10:39:04