我需要像这样转换列表列表:
[['S', 'NP', 'VP'], ['NP', 'Det', 'N'], ['NP', 'NP', 'PP'], ['VP', 'V', 'NP'], ['VP', 'VP', 'PP'], ['PP', 'P', 'NP'], ['Det', "'the'"], ['N', "'pirate'"], ['N', "'sailor'"], ['N', "'telescope'"], ['V', "'sees'"], ['P', "'with'"]]
到一本看起来像这样的字典:
{'S':['NP', 'VP'], 'NP': ['Det', 'N'], ['NP', 'PP'], 'VP': ['V', 'NP'], ['VP', 'PP'], 'PP': ['P', 'NP'], 'Det': ["'the'"], 'N': ["'pirate'"], ["'sailor'"], ["'telescope'"], 'V': ["'sees'"], 'P': ["'with'"]}
我尝试使用from collections import default dict
使用此方法:
g = defaultdict(dict)
for i, j, k in new_grammar:
g[i][j] = k
但这不起作用,因为列表列表中有只包含两个元素的列表。你知道吗
我也尝试过:
grammar = {}
for rule in new_grammar:
grammar[rule[0]] = rule[1:]
但是,这只给每个键一个值。你知道吗
有什么办法吗?你知道吗
这是使用
collections.defaultdict
的一种方法。你知道吗请注意,结果是一个字典,其中包含分配给每个键的值列表。这不是您定义所需输出的方式,这在Python中是无效的。你知道吗
为什么不只是这个?或者这就是你想要的?地址:
输出:
您的方法是正确的,但是defaultdict是从字符串到列表的映射,而不是dictionary。试试这个:
相关问题 更多 >
编程相关推荐