加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 三重嵌套字典理解?

发布时间:2020-12-20 11:53:42 所属栏目:Python 来源:网络整理
导读:假设我有一个熊猫系列,像这样: import pandas as pds = pd.Series(["hello go home bye bye","you can't always get","what you waaaaaaant","apple banana carrot munch 123"]) 我想创建一个字典,其中单个字符作为键,其频率作为值.在集合的帮助下,为过去的
假设我有一个熊猫系列,像这样:

import pandas as pd
s = pd.Series(["hello go home bye bye","you can't always get","what you waaaaaaant","apple banana carrot munch 123"])

我想创建一个字典,其中单个字符作为键,其频率作为值.在集合的帮助下,为过去的单词创建这些词典很容易.计数器:

from collections import Counter
c = Counter(word for row in s for word in row.lower().split())

但是,我现在正在尝试存储单个字符,并且在三嵌套字典理解方面存在一些问题.这就是我所拥有的:

c = Counter((letter for letter in word) for word for row in s for word in row.lower().split())

这给了我一个语法错误.如何在一行中创建等效的以下for循环?

d = {}
for row in s:
    for word in row.lower().split():
        for letter in word:
            d[letter] += 1

解决方法

我想你可以用

Counter([j for i in s for j in i])
Counter({'a': 16,' ': 13,'e': 6,'o': 6,'n': 5,'t': 5,'y': 5,'h': 4,'l': 4,'c': 3,'b': 3,'u': 3,'w': 3,'g': 2,'m': 2,'p': 2,'r': 2,"'": 1,'1': 1,'3': 1,'2': 1,'s': 1})

获得个人字符数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读