首页 > 解决方案 > 字典中每个键的嵌套列表总和

问题描述

您如何获得下面字典中每个键的每个嵌套列表的总和?

假设下面的内容称为 msgs

在此处输入图像描述

我尝试了以下代码:

在此处输入图像描述

我最终得到了结果:

在此处输入图像描述

这几乎是正确的,但由于某种原因,第一个嵌套列表的总和不正确,为 0 而应该为 19。我感觉这与我编写的上述代码中的 total = 0 部分有关,但我不是确定是否是这种情况,我不知道如何解决这个问题。

我在嵌套列表中获取值的方式是将嵌套列表的每个索引中的字符串数相加。例如,这里是第一个键。如您所见,第一个条目中有 15 个条目,第二个条目中有 4 个条目。

(这本词典在我的代码中称为“kakao”)

{'Saturday, July 28, 2018': [['hey', 'ben', 'u her?', 'here?', 'ok so basically', 'farzam and avash dont wanna go to vegas', 'lol', 'im offering a spontaneous trip me and you to SF', 'lol otherwise ill just go back to LA', 'i mean sf is far but', 'i mean if u really wanna hhah', 'we could go and see chris', 'but otherwise its fine', 'alright send me the code too', 'im on my way right now'], ['Wtf is happening lol', '8 haha', 'Key is #8000', 'Hf']]}

我用来将总和作为嵌套列表的代码是:

在此处输入图像描述

标签: pythonalgorithmdictionarynested-lists

解决方案


kakao = {'Saturday, July 28, 2018': [['hey', 'ben', 'u her?', 'here?', 'ok so basically', \
'farzam and avash dont wanna go to vegas', 'lol', 'im offering a spontaneous trip me and you to SF', \
'lol otherwise ill just go back to LA', 'i mean sf is far but', 'i mean if u really wanna hhah', \
'we could go and see chris', 'but otherwise its fine', 'alright send me the code too', 'im on my way right now'], \
['Wtf is happening lol', '8 haha', 'Key is #8000', 'Hf']],
'Friday, August 3, 2018': [['Someone', 'said', 'something'], ['Just', 'test']],}


print({key: [sum(map(lambda letters: len(letters), val))] for key, val in kakao.items()})


#the result --> {'Saturday, July 28, 2018': [19], 'Friday, August 3, 2018': [5]}

我猜你想在同一天计算句子中的字母,希望这个代码可以帮助你。


推荐阅读