[英]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.