天天看點

python字典嵌套字典_python – 三重嵌套字典了解?

假設我有一個熊貓系列,像這樣:

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

獲得個人字元數.