1

誰かがこの Python 辞書タプルを読むのを手伝ってくれますか? 私はPythonに慣れていないので、あまり活用できません

Grammar = {'AB':('S', 'B'), 'BB':'A', 'a':'A', 'b':'B'}

注: 文法は Context Free Grammar の文法です。

4

1 に答える 1

1

辞書を必要なものに変換するには、次のようにします。

>>> from collection import defaultdict
>>> grammar = {'AB':('S', 'B'), 'BB':'A', 'a':'A', 'b':'B'}
>>> tmp_result = defaultdict(list)
>>> def tuplify(val):
...     if not isinstance(val, tuple):
...         val = (val,)
...     return val
... 
>>> for key, value in grammar.items():
...     values = tuplify(value)
...     for val in values:
...         tmp_result[val].append(key)
... 
>>> tmp_result
defaultdict(<type 'list'>, {'A': ['a', 'BB'], 'S': ['AB'], 'B': ['AB', 'b']})
>>> result = {key:tuple(val) for key, val in tmp_result.items()}
>>> result
{'A': ('a', 'BB'), 'S': ('AB',), 'B': ('AB', 'b')}

クラスcollections.defaultdictdict、キーが欠落しているときにファクトリを使用してデフォルト値を作成する のようなクラスです。たとえば、次のように記述します。

>>> D = defaultdict(list)
>>> D[5].append(3)
>>> D[5]
[3]

dict次のような通常の sを使用して記述できます。

>>> D = {}
>>> if 5 in D: # key present, use that value
...     val = D[5]
... else:      # otherwise create a default value and sets it
...     val = list()
...     D[5] = val
... 
>>> val.append(3)
>>> D[5]
[3]

に渡される「ファクトリ」はdefaultdict(factory)、引数を受け取らない任意の callable にすることができます。次に例を示します。

>>> n = 0
>>> def factory():
...     global n
...     print('Factory called!')
...     n += 1
...     return n   #returns numbers 1, 2, 3, 4, ...
... 
>>> D = defaultdict(factory)
>>> D[0]
Factory called!
1
>>> D[0]   # the keys exists, thus the factory is not called.
1
>>> D[1]
Factory called!
2
>>> D[1]
2
于 2013-04-07T08:23:39.157 に答える