, {._最多单词数的发">
赞
踩
首先解决messages列表中每一条信息的单词数量,即 words = message[i].cout(" ")+1
其次是建立一个字典,键是sender 值是该发送者发送的单词数量,那么这个使用defaultdcit就能完美解决,cnt = defaultdict(int) cnt[sender]+=words
那么我们最后一个字典,键是每一个sender,值是他所有发送的所有单词数,例如上述的例子中,最后生成的cnt为:defaultdict(<class 'int'>, {'Alice': 5, 'userTwo': 2, 'userThree': 3})
,我们如何提取出单词数最多的发件人名字呢?
这里我们可能会想到返回这个字典的.items()
即生成一个这样的列表 dict_items([('Alice', 5), ('userTwo', 2), ('userThree', 3)])
但是这样并不好使用max()返回最大值,我们更希望将第一位和第二位调换一下位置,即(5, 'Alice'), (2, 'userTwo'), (3, 'userThree')]
,这样的话就可以直接使用max函数进行返回,那么怎么实现呢?使用map函数可以完美解决。
map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新迭代器,注意这里是迭代器,如果想要返回list,需要list(map(function,iterable,...))
map() 函数语法:
map(function,iterable,...)
# 其中function---函数,iterable---一个或多个序列
实例:
>>> def square(x) : # 计算平方数
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
<map object at 0x100d3d550> # 返回迭代器
>>> list(map(square, [1,2,3,4,5])) # 使用 list() 转换为列表
[1, 4, 9, 16, 25]
>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
>>>
所以承接本题,我们可以利用map函数将cnt的第一位和第二位调换一下 a = list(map(lambda x: (x[1], x[0]), cnt.items()))
,最后return max(a)[1]
就ok了
from collections import defaultdict
class Solution:
def largestWordCount(self, messages: List[str], senders: List[str]) -> str:
cnt = defaultdict(int)
for message, sender in zip(messages, senders):
cnt[sender] += message.count(' ') + 1
print(cnt)
print(cnt.items())
a = list(map(lambda x: (x[1], x[0]), cnt.items()))
return max(a)[1]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。