gpt4 book ai didi

python - 列表中的一个值,python

转载 作者:太空狗 更新时间:2023-10-30 01:49:16 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com