gpt4 book ai didi

python - Python 中的嵌套默认值

转载 作者:太空宇宙 更新时间:2023-11-03 12:56:06 24 4
gpt4 key购买 nike

我在更新嵌套 defaultdict 中的列表时遇到问题。

这是我的代码:

a = ['20160115',    'shadyside medical building',   1, 'Review']
b = ['20160115', 'shadyside medical building', 1, 'Video']
c = ['20160215', 'shadyside medical building', 1, 'Video']
d = ['20160215', 'medical building', 1, 'Video']
f = [a,b,c,d]

nested_dict = defaultdict(dict)

for date,keyword,pos,feature in f:
nested_dict[keyword].update({feature : [pos]})
nested_dict[keyword].update({feature : [pos]})

这是输出:

{'shadyside medical building': 
{'Review': [1],
'Video': [1]},
'medical building':
{'Video': [1]}}

期望的输出是:

{'shadyside medical building': 
{'Review': [1],
'Video': [1,1]},
'medical building':
{'Video': [1]}}

请注意视频的第二项已添加到视频列表中。

最佳答案

您没有嵌套任何 defaultdict,所以这样做:

nested_dict = defaultdict(lambda: defaultdict(list))

nested_dict[keyword][feature].append(pos)

关于python - Python 中的嵌套默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41571459/

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