【发布时间】:2018-05-19 18:01:12
【问题描述】:
我正在尝试编写一个代码,我可以在其中输入一个随机句子,并计算一个字母在此字符串中返回的次数:
def getfreq(lines):
""" calculate a list with letter frequencies
lines - list of lines (character strings)
both lower and upper case characters are counted.
"""
totals = 26*[0]
chars = []
for line in lines:
for ch in line:
chars.append(totals)
return totals
# convert totals to frequency
freqlst = []
grandtotal = sum(totals)
for total in totals:
freq = totals.count(chars)
freqlst.append(freq)
return freqlst
到目前为止,我已经将输入的每个字母附加到列表(字符)中。但是现在我需要一种方法来计算一个字符在该列表中返回的次数,并以频率表示。
【问题讨论】:
-
为什么你的函数有 2 个
return语句?第二部分永远不会运行... -
更好的组织结果的方法可能是使用字典,例如
{'a': 5, 'b': 2, 'G': 7, ... }
标签: python list count frequency