Python扁平化我的元组结构

时间:2013-03-07 10:04:30

标签: python python-2.7 tuples

我正在尝试使用带有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()    

1 个答案:

答案 0 :(得分:2)

您需要添加逗号:

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)

只有在需要定义元组时才需要括号:

>>> ()
()