[英]How to return maximum of value in a tuple within a list within a dictionary?
這是 RM Lerner 的 Python Workout 書中的一個練習。
我正在努力返回以下代碼的最大值:
def most_repeating_word(ls):
listed = [x for x in ls.split()]
outcome = {}
for word in listed:
max_char = []
char_set = []
for char in word:
if char not in char_set:
char_set.append(char)
count = word.count(char)
max_char.append((char,count))
outcome[word] = (max_char)
return max(outcome, key = lambda x: x[1])
most_repeating_word('this is an elementary test example')
該函數應返回具有最高重復元素的單詞,在本例中為 e=3 的“elementary”,但它返回“example”。
我認為原因是它比較了單詞的第二個字母,並返回“x”作為最大值。 我不明白如何訪問元組值。 在返回部分使用outcome.values
沒有幫助。
我們可以在outcome
字典上使用for loop
來檢查哪個單詞中哪個字母重復最多。
def most_repeating_word(ls):
listed = [x for x in ls.split()]
outcome = {}
for word in listed:
max_char = []
char_set = []
for char in word:
if char not in char_set:
char_set.append(char)
count = word.count(char)
max_char.append((char,count))
outcome[word] = (max_char)
repeating_word = ''
repeating_letter = ''
max_char_count = 0
for key in outcome:
for letter in outcome[key]:
if letter[1] > max_char_count:
repeating_word = key
repeating_letter = letter[0]
max_char_count = letter[1]
return [repeating_word, repeating_letter, max_char_count]
data = most_repeating_word('this is an elementary test example')
print(f"The word {data[0]} ham most repeated letter {data[1]} which occurs {data[2]} times")
The word elementary ham most repeated letter e which occurs 3 times
由於outcome
是元組列表的字典,因此您需要兩個max()
來查找具有最高重復元素的單詞。 第一個max()
查找單詞中重復次數最多的元素的計數,第二個max()
查找計數最高的單詞。
保留您使用的數據結構, key
參數需要如下所示: lambda word_maxchar: max(word_maxchar[1], key = lambda char_count: char_count[1])[1]
。 整個代碼如下所示:
def most_repeating_word(ls):
listed = [x for x in ls.split()]
outcome = {}
for word in listed:
max_char = []
char_set = []
for char in word:
if char not in char_set:
char_set.append(char)
count = word.count(char)
max_char.append((char,count))
outcome[word] = (max_char)
return max(outcome.items(), key = lambda word_maxchar: max(word_maxchar[1], key = lambda char_count: char_count[1])[1])[0]
most_repeating_word('this is an elementary test example')
另請注意,為了遍歷字典的鍵和值,您需要使用outcome.items()
。
通過對你的數據結構稍作修改,我們可以實現代碼的稍微更好的可讀性:
def most_repeating_word(ls):
listed = [x for x in ls.split()]
outcome = {}
for word in listed:
max_char = []
char_set = []
for char in word:
if char not in char_set:
char_set.append(char)
count = word.count(char)
max_char.append((char,count))
outcome[word] = max(max_char, key = lambda char_count: char_count[1])
return max(outcome.items(), key = lambda x: x[1][1])[0]
most_repeating_word('this is an elementary test example')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.