【问题标题】:Sum of Nested Lists for each key in dictionary字典中每个键的嵌套列表总和
【发布时间】:2018-12-13 07:34:10
【问题描述】:

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

假设下面称为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']]}

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

【问题讨论】:

  • 请粘贴代码 sn-ps 而不是代码图片。
  • 每个项目的深度级别是否事先已知?
  • 我添加了一些额外的信息
  • 没关系,我明白了!我想通了
  • 在代码块中粘贴代码,不要使用图片。

标签: python algorithm dictionary nested-lists


【解决方案1】:
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]}

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

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 2022-01-21
    • 2020-12-15
    • 2021-05-10
    • 2023-04-02
    • 1970-01-01
    • 2020-09-15
    • 2023-03-29
    • 2021-06-13
    相关资源
    最近更新 更多