假设我有一个pandas
Series
,如下所示:
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"])
我想创建一个以单个字符为键,以其频率为值的字典在
collections.Counter
的帮助下,为过去的单词创建这些词典很容易:from collections import Counter
c = Counter(word for row in s for word in row.lower().split())
但是,我现在试图存储单个字符,并且在三重嵌套的dict理解方面遇到了一些问题以下是我所拥有的:
c = Counter((letter for letter in word) for word for row in s for word in row.lower().split())
这给了我一个语法错误。我如何在一行中使下列循环等价?
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})
获取单个字符计数。
关于python - 三重嵌套字典理解?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39020492/