0

マップを使用して Python 階層データ構造を作成しようとしていますが、値はタプルになります。場合によっては、タプルの長さは 1 になります。Python は、タプルの長さが 1 の場合は常に構造をインテリジェントにフラット化します。Python インタープリターで実行できる以下の例を観察してください。「another_scenario」では、長さが 1 であると予想していましたが、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()    
4

1 に答える 1

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)

括弧は、空のタプルを定義する必要がある場合にのみ必要です。

>>> ()
()
于 2013-03-07T10:20:37.203 に答える