python - 列表中的一个值,python

标签 python python-3.x

英语中的每个字符都有出现的百分比,这些是百分比:

A       B       C       D       E       F       G       H       I
.0817   .0149   .0278   .0425   .1270   .0223   .0202   .0609   .0697
J       K       L       M       N       O       P       Q       R
.0015   .0077   .0402   .0241   .0675   .0751   .0193   .0009   .0599
S       T       U       V       W       X       Y       Z   
.0633   .0906   .0276   .0098   .0236   .0015   .0197   .0007

名为 letterGoodness 的列表预定义为:

letterGoodness = [.0817,.0149,.0278,.0425,.1270,.0223,.0202,...

我需要找到字符串的“优点”。例如,“我吃”的好处是:.0697 + .1270 + .0817 + .0906 =.369。这是一个更大问题的一部分,但我需要解决这个问题才能解决这个大问题。我是这样开始的:

def goodness(message):
   for i in L:
     for j in i:

因此,找出如何获取任何字符的出现百分比就足够了。你能帮助我吗? 该字符串仅包含大写字母和空格。

最佳答案

letterGoodness 作为字典更好,那么你可以这样做:

sum(letterGoodness.get(c,0) for c in yourstring.upper())
#                                             #^.upper for defensive programming

要将列表中的 letterGoodness 转换为字典,您可以执行以下操作:

import string
letterGoodness = dict(zip(string.ascii_uppercase,letterGoodness))

如果你保证只有大写字母和空格,你可以这样做:

letterGoodness = dict(zip(string.ascii_uppercase,letterGoodness))
letterGoodness[' '] = 0
sum(letterGoodness[c] for c in yourstring)

但这里的性能提升可能非常小,所以我更喜欢上面更强大的版本。


如果您坚持将 letterGoodness 保留为列表(我不建议这样做),您可以使用内置的 ord 来获取索引(由克沃伦普尔):

 ordA = ord('A')
 sum(letterGoodness[ord(c)-ordA] for c in yourstring if c in string.ascii_uppercase)

我现在懒得timeit,但你可能还想定义一个临时集来保存string.ascii_uppercase——它可能会让你的函数运行快一点(取决于 str.__contains__set.__contains__ 的优化程度):

 ordA = ord('A')
 big_letters = set(string.ascii_uppercase)
 sum(letterGoodness[ord(c)-ordA] for c in yourstring.upper() if c in big_letters)

关于python - 列表中的一个值,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12112200/

相关文章:

python - SQLAlchemy - 类型错误 : Boolean value of this clause is not defined

python - Discord.py - 如何制定角色特定命令?

python - 打印来自 Python 生成器的所有结果

python - Win8 上的 GTK3 小字体和条目

python - 使用 boto (AWS Python),如何获取 IAM 用户列表?

python - 在 Python 3 中读取 MP3

python - 将元组列表转换为 numpy 数组

javascript - PyQT4: "TypeError: Attempting to configurable attribute of unconfigurable property."

python - 如何在 Python 中使用 matplotlib 创建子图

c# - 为 .NET 开发人员学习 Python