字典中每个键的嵌套列表总数

时间:2018-12-13 07:34:11

标签: python algorithm dictionary nested-lists

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

比方说以下称为msgs

enter image description here

我尝试了以下代码:

enter image description here

我最终得到了结果:

enter image description here

这几乎是正确的,但是由于某些原因,第一个嵌套列表的总和不正确,为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']]}

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

enter image description here

1 个答案:

答案 0 :(得分:0)

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]}

我想您想同时计算句子中的字母,希望这段代码对您有所帮助。