如何将具有相同第一个元素的独立列表的列表转换为字典?

2024-10-02 02:34:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要像这样转换列表列表:

[['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:]

但是,这只给每个键一个值。你知道吗

有什么办法吗?你知道吗


Tags: the列表forwithnpruledictpp
3条回答

这是使用collections.defaultdict的一种方法。你知道吗

请注意,结果是一个字典,其中包含分配给每个键的值列表。这不是您定义所需输出的方式,这在Python中是无效的。你知道吗

L = [['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'"]]

from collections import defaultdict

d = defaultdict(list)

for k, *v in L:
    d[k].extend(v)

print(d)

defaultdict(list,
            {'Det': ["'the'"],
             'N': ["'pirate'", "'sailor'", "'telescope'"],
             'NP': ['Det', 'N', 'NP', 'PP'],
             'P': ["'with'"],
             'PP': ['P', 'NP'],
             'S': ['NP', 'VP'],
             'V': ["'sees'"],
             'VP': ['V', 'NP', 'VP', 'PP']})

为什么不只是这个?或者这就是你想要的?地址:

l = [['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'"]]
print(dict(zip([i[0] for i in l],[i[1:] for i in l])))

输出:

{'S': ['NP', 'VP'], 'NP': ['NP', 'PP'], 'VP': ['VP', 'PP'], 'PP': ['P', 'NP'], 'Det': ["'the'"], 'N': ["'telescope'"], 'V': ["'sees'"], 'P': ["'with'"]}

您的方法是正确的,但是defaultdict是从字符串到列表的映射,而不是dictionary。试试这个:

g = defaultdict(list)
for i in new_grammar:
    g[i[0]].extend(i[1:])

相关问题 更多 >

    热门问题