如果a为1,b为2,c为3,我试图让程序计算每个单词的值,依此类推。我已经制作了大部分代码,但它不起作用。有人能给我一些建议吗?我刚刚开始学习python,所以你能尽可能详细吗?谢谢。
__author__ = "Anthony Chen"
__copyright__ = "Copyright (C) 2017 Anthony Chen"
__license__ = "Public Domain"
__version__ = "1.0"
output = ('None')
worth = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5,
'f':6,
'g':7,
'h':8,
'i':9,
'j':10,
'k':11,
'l':12,
'm':13,
'n':14,
'o':16,
'q':17,
'r':18,
's':19,
't':20,
'u':21,
'v':22,
'w':23,
'x':24,
'y':25,
'z':26,
}
def findworth():
for char in wordlist:
if char in wordlist:
output = (worth[char])
wordlist.replace(output)
elif worth[char] == False:
output = (None)
while True:
output = (None)
wordlist = []
word = input(str("Find out how many cents your word is worth. Please enter your word:"))
word = word.lower()
wordlist = list(word)
wordlist = findworth()
output = sum(wordlist)
print("Your word's value is:")
print (output)
print('.')
这是我运行时显示的内容:
**Find out how many cents your word is worth. Please enter your word:Bananas
Traceback (most recent call last):
File "C:/Anthony/School/__CentsWord/WordWorth.py", line 49, in <module>
wordlist = findworth()
File "C:/Anthony/School/__CentsWord/WordWorth.py", line 39, in findworth
wordlist.replace(output)
AttributeError: 'list' object has no attribute 'replace'**
答案 0 :(得分:1)
对于避免使用更高级技术的解决方案:
worth = {
'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7,
'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14,
'o':15, 'q':17, 'r':18, 's':19, 't':20, 'u':21,
'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
def findworth(word):
total = 0
for char in word:
if char in worth:
total += worth[char]
return total
print("Find out how many cents your word is worth.")
while True:
word = input("Please enter your word: ").lower()
print("Your word's value is:", findworth(word))
按如下方式输出:
Find out how many cents your word is worth.
Please enter your word: abc
Your word's value is: 6
Please enter your word: hello
Your word's value is: 53
注意: worth
目前缺少p
,o
值不正确,应该是:
worth = {
'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7,
'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14,
'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21,
'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
答案 1 :(得分:0)
根据你的解决方案(它不是很好的imo,会提供更好的解决方案)
def findworth():
for i,char in enumerate(wordlist):
if char in worth:
output = (worth[char])
wordlist[i] = (output)
else:
output = (None)
while True:
output = (None)
wordlist = []
word = input(str("Find out how many cents your word is worth. Please enter your word:"))
word = word.lower()
wordlist = list(word)
findworth()
output = sum(wordlist)
print("Your word's value is:")
print (output)
print('.')
减少冗余的更好解决方案
while True:
word = input(str("Find out how many cents your word is worth. Please enter your word:"))
word = word.lower()
output = 0 # set initial value
for char in word: # iterate string for each character
if char in worth: # check if its a valid char
output += worth[char] # same as output = output + worth[char]
print("Your word's value is:")
print (output)
print('.')
Python的字符串已经可以迭代,所以你不必把它变成一个列表:)
答案 2 :(得分:0)
我的第一个评论是,用于生成worth
的方法很长,很容易出错,事实上,您似乎忘记了'p'
而是使用了{{1} }}。您可以使用字典理解生成您的价值清单:
'o':16
这可以通过循环数字1..26,并将worth = {chr(x+96):x for x in range(1,27)}
转换为字符(使用ASCII表来查看97是n + 96
,98是'a'
等等然后,将此字符用作值的键。
接下来,我们可以为单词中的每个字符生成一个值列表:
'b'
这会给我们word = "hello"
scores = [worth[c] for c in word]
。
最后,您可以调用scores == [8, 5, 12, 12, 5]
函数来添加列表中的所有值:
sum
返回sum(scores)
。
你可以将它们组合成一个函数来获取:
52
或者,这可以在1行上完成:
def get_word_score(word):
worth = {chr(x+96):x for x in range(1,27)}
scores = [worth[c] for c in word]
return sum(scores)
sum([ord(c)-96 for c in word])
与ord
相反,它返回给定字符的ASCII值。
使用chr
一词sum([ord(c)-96 for c in word])
的演练。第一步是将每个角色放入一个列表中:
'hello'
接下来将每个字符转换为ASCII值:
>>> [c for c in 'hello']
['h', 'e', 'l', 'l', 'o']
接下来,通过减去96:
将每个ASCII值转换为字母位置>>> [ord(c) for c in 'hello']
[104, 101, 108, 108, 111]
最后总结:
>>> [ord(c)-96 for c in 'hello']
[8, 5, 12, 12, 15]
您的代码功能是:
>>> sum([ord(c)-96 for c in 'hello'])
52