我想要一個具有映射的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()
如果我更換()用[]即,使用左旋在上面的元組ist insted我得到我期望的輸出。我不想使用列表,雖然 – 2013-03-07 10:09:26