python - 字典中每个键的嵌套列表总和
问题描述
您如何获得下面字典中每个键的每个嵌套列表的总和?
假设下面的内容称为 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']]}
我用来将总和作为嵌套列表的代码是:
解决方案
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]}
我猜你想在同一天计算句子中的字母,希望这个代码可以帮助你。
推荐阅读
- javascript - 在 iOS Safari 中,getUserMedia 的权限在一分钟后超时
- python - 退出后程序继续执行
- batch-file - 使用 teraterm API 调用 'setexitcode' 设置 WIndows 系统变量 %errorlevel% 需要 2 个 teraterm 会话才能注册
- javascript - md5 字符串的 base64_encoding - php vs javascript 问题
- android - android array adapter.notifyDataSetChanged() 正在改变项目的位置
- c# - 状态码 403 禁止无法在 wsdl webservice 上使用 postAsync 方法对多部分数据进行编码?
- rest - 使用联合安全性授权 REST API 的最佳实践是什么?
- java - Keycloak - 如何用 Java 客户端刷新令牌?
- unity3d - 直接在文本编辑器中双击打开所有类型的文件
- jquery - 为什么 Bootstrap 自动完成选择无法正常工作?