我想弄清楚如何计算两个合并的名单列表的得分。我需要为每个字符(包括名字和姓氏之间的空格)加一个点,并为名称中的每个元音添加一个点。
<%= form_tag(products_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search products" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
我正在努力弄清楚要做什么。任何帮助将不胜感激。
答案 0 :(得分:1)
首先是zip
名字和姓氏,然后以str
为' '
作为分隔符。然后用collections.Counter
计算所谓的元音字符出现次数,sum
它们,并添加全名len
。那将是dict
对象,然后你可以随心所欲地做任何事情。
from collections import Counter
a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = ["a", "e", "i", "o", "u"]
output = {}
for item in [' '.join(i) for i in zip(a,b)]:
output[item] = sum(Counter(item)[x] for x in vowel) + len(item)
output
输出:
{'John Green': 13, 'Kate Fletcher': 17, 'Oli Nelson': 13}
<强>更新强>
如果您需要名字和姓氏的所有可能变体,则可以使用itertools.product
from itertools import product
from collections import Counter
a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = ["a", "e", "i", "o", "u"]
output = {}
for item in [' '.join(i) for i in product(a,b)]:
output[item] = sum(Counter(item)[x] for x in vowel) + len(item)
output
输出:
{'John Fletcher': 16,
'John Green': 13,
'John Nelson': 14,
'Kate Fletcher': 17,
'Kate Green': 14,
'Kate Nelson': 15,
'Oli Fletcher': 15,
'Oli Green': 12,
'Oli Nelson': 13}
答案 1 :(得分:0)
for first, second in gen:
name = " ".join(first, second)
score = 0
for letter in name:
if letter in vowel:
score += 1
score += len(name)
将它们作为字符串更容易,然后可以循环遍历该字符串。每个字符一个点很容易,这只是字符串的长度。如果元音是一个额外的字母,只需循环字母,如果元音添加一个点。瞧!