我正在尝试使用一个带有map的python分层数据结构,值将是一个元组。在某些情况下,元组的长度为1。只要元组的长度为1,Python就会智能地展平结构。观察下面的示例,该示例可以在python解释器中运行。在"another_scenario“中,我预计长度是1,但它已经钻到了下面的一个级别,并获得了底层步骤。这完全搞砸了我的测试,因为我依赖于它是一个带有命令function_list函数列表的元组。
问题-为什么会发生这种情况?我怎么让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() 发布于 2013-03-07 18:20:37
您需要添加逗号:
another_scenario = {
"scenario_name":
(
(
"command1",
(
os.path,
os.path.exists
),
None
), # <- Note this comma
)
}使其成为元组,否则它只是一个表达式。1元素元组只能通过逗号的存在与表达式区分开来:
>>> (1)
1
>>> (1,)
(1,)
>>> type((1))
<type 'int'>
>>> type((1,))
<type 'tuple'>事实上,定义元组的是逗号,而不是括号:
>>> 1,
(1,)
>>> 1, 2
(1, 2)仅当需要定义空元组时,才需要使用括号:
>>> ()
()https://stackoverflow.com/questions/15268210
复制相似问题