gpt4 book ai didi

python - 在 Python 中为字典中的值制作字典

转载 作者:太空狗 更新时间:2023-10-29 23:58:30 26 4
gpt4 key购买 nike

我正在尝试添加字典,该字典具有来自列表中每个元素的键和来自列表中一个后续元素的值以及它后面的次数计数,采用字典格式。例如,如果我们有单词列表,['The', 'cat', 'chased', 'the', 'dog'] 如果键是“the”,我想值为 {'dog': 1, 'cat': 1}。整个输出应该是 {'the': {'dog': 1, 'cat': 1}, 'chased': {'the': 1}, 'cat': {'chased': 1} }

到目前为止,我的代码可以生成键和值,但不能以字典格式生成字典。有人可以帮忙吗?

我的代码:

line = ['The', 'cat', 'chased', 'the', 'dog']
output = {}
for i, item in enumerate(line):
print(i, item, len(line))
if i != len(line) - 1:
output[item] = line[i+1]=i
print(output)

输出:

{'The': 'cat', 'chased': 'the', 'the': 'dog', 'cat': 'chased'}

最佳答案

我没有测试过,但也许是这样的?使用 defaultdict:

from collections import defaultdict

line = ['The', 'cat', 'chased', 'the', 'dog']
output = defaultdict(lambda: defaultdict(int))

for t, token in enumerate(line[:-1]):
output[token.lower()][line[t + 1].lower()] += 1

关于python - 在 Python 中为字典中的值制作字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31693708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com