我想弄清楚如何计算两个合并的名单列表的得分。我需要为每个字符(包括名字和姓氏之间的空格)加一个点,并为名称中的每个元音添加一个点。我现在可以计算名称长度的分数,但无法弄清楚如何包含元音的数量。
a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = ["a", "e", "i", "o", "u"]
gen = ((x, y) for x in a for y in b)
score = 0
for first, second in gen:
print first, second
name = first, second
score = len(first) + len(second) +1
for letter in name:
if letter in vowel:
score+1
print score
这就是我现在所拥有的,这是我得到的输出:
John Green
10
John Fletcher
13
John Nelson
11
Kate Green
10
Kate Fletcher
13
Kate Nelson
11
Oli Green
9
Oli Fletcher
12
Oli Nelson
10
这是我需要的输出:
Full Name: John Green Score: 13
Full Name: John Fletcher Score: 16
Full Name: John Nelson Score: 14
Full Name: Kate Green Score: 14
Full Name: Kate Fletcher Score: 17
Full Name: Kate Nelson Score: 15
Full Name: Oli Green Score: 13
Full Name: Oli Fletcher Score: 16
Full Name: Oli Nelson Score: 14
答案 0 :(得分:2)
您不计算元音的原因是得分变量没有增加。要增加它,您必须将变量分数设置为先前分数+1。
这应该有效:
for letter in name:
if letter in vowel:
score+=1
编辑:值得一提的是,得分+ = 1与得分=得分+ 1
相同我计算出了错误 - 而不是创建name = first,second,将name初始化为first + second。您将获得所需的结果。失败的原因是因为name = first,second创建了一个元组,并且通过元组迭代使得letter =" Kate"," John"等,而不是实际的个人角色。
答案 1 :(得分:1)
a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = {"a", "e", "i", "o", "u"}
names = (first + ' ' + last for first in a for last in b)
for name in names:
score = len(name) + sum(c in vowel for c in name.lower())
print "Full Name: {name} Score: {score}".format(name=name, score=score)
Full Name: John Green Score: 13
Full Name: John Fletcher Score: 16
Full Name: John Nelson Score: 14
Full Name: Kate Green Score: 14
Full Name: Kate Fletcher Score: 17
Full Name: Kate Nelson Score: 15
Full Name: Oli Green Score: 13
Full Name: Oli Fletcher Score: 16
Full Name: Oli Nelson Score: 14