3 回答

TA贡献1876条经验 获得超5个赞
不使用更新的@Primusa 答案的变体:
from collections import Counter
words = ["tree", "bone", "indigo", "developer"]
counts = Counter(c for word in words for c in set(word.lower()) if c.isalpha())
输出
Counter({'e': 3, 'o': 3, 'r': 2, 'd': 2, 'n': 2, 'p': 1, 'i': 1, 'b': 1, 'v': 1, 'g': 1, 'l': 1, 't': 1})
基本上将每个单词转换为一个集合,然后迭代每个集合。

TA贡献1946条经验 获得超3个赞
创建一个计数器对象,然后用每个单词的集合更新它:
from collections import Counter
wordlist = ["tree","bone","indigo","developer"]
c = Counter()
for word in wordlist:
c.update(set(word.lower()))
print(c)
输出:
Counter({'e': 3, 'o': 3, 'r': 2, 'n': 2, 'd': 2, 't': 1, 'b': 1, 'i': 1, 'g': 1, 'v': 1, 'p': 1, 'l': 1})
请注意,虽然 中不存在的字母wordlist不存在于 中Counter,但这很好,因为 a 的Counter行为类似于 a defaultdict(int),因此访问不存在的值会自动返回默认值 0。

TA贡献1777条经验 获得超3个赞
一个没有柜台
words=["tree","bone","indigo","developer"]
d={}
for word in words: # iterate over words
for i in set(word): # to remove the duplication of characters within word
d[i]=d.get(i,0)+1
输出
{'b': 1,
'd': 2,
'e': 3,
'g': 1,
'i': 1,
'l': 1,
'n': 2,
'o': 3,
'p': 1,
'r': 2,
't': 1,
'v': 1}
添加回答
举报