[英]Python - Scrabble_score
Can someone break down the individual components that make up scrabble_score: 有人可以分解构成scrabble_score的各个组件吗:
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
def scrabble_score(word):
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
The structure is a list comprehension. 该结构是列表理解。 This is a terse way of creating a list from an iterable.
这是从迭代器创建列表的简洁方法。 See below where the
1
s are list comps and the 2
s are traditional for
loops. 见下面,其中
1
s为列表谱曲和2
s为传统for
循环。
result1 = [some_value for element in iterable]
# where the group of "value" statements is the final list
result2 = []
for element in iterable:
result2.append(some_value)
example1 = [x**2 for x in range(10)] # [0**2, 1**2, 2**2, ..., 9**2]
example2 = []
for x in range(10):
example2.append(x)
This particular listcomp is using a dict lookup ( score[x]
) as the value of the list, where x
is each element of word.replace(" ", "").lower()
. 这个特定的listcomp使用dict查找(
score[x]
)作为列表的值,其中x
是word.replace(" ", "").lower()
每个元素。 It also uses a conditional filtering statement at the end to make sure it only selects those elements where x
is in score
(so something like it's
doesn't fail on the '
.) 它还使用条件过滤语句的结束,以确保它只会选择其中那些元素
x
是在score
(所以像it's
在不会失败'
。)
Wrapped around it is sum
, which simply adds all the numbers in a list and gives the result. 包裹在它周围的是
sum
,它只是将列表中的所有数字相加并给出结果。
broken down (in bold)... 细分(以粗体显示)...
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
removes all spaces and converts to all lower case 删除所有空格并转换为所有小写字母
return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
for each letter after removing spaces and converting to lower case 删除空格并转换为小写后的每个字母
return sum([score[x] for x in word.replace(" ", "").lower() if x in score ])
if that letter is in the score dictionary 如果该字母在分数字典中
return sum([ score[x] for x in word.replace(" ", "").lower() if x in score])
get the score for that letter and add it to a list 获得该字母的分数并将其添加到列表中
return sum([ score[x] for x in word.replace(" ", "").lower() if x in score ])
after getting the score for each letter, add up the sum of the resulting list of values and return 得到每个字母的分数后,将结果列表的总和相加并返回
you can use this code for solution 您可以使用此代码作为解决方案
total_score variable is to sum letter score. total_score变量用于求和字母得分。 the score[char.lower()] is for code that will work even if the letters you get are uppercase, lowercase, or a mix
score [char.lower()]用于即使您得到的字母是大写,小写或混合字母也可以使用的代码
def scrabble_score (word):
total_score=0
for char in word:
total_score+=score[char.lower()]
return total_score
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.