python - 计算列表字典中最流行的项目python
问题描述
我有一本看起来像这样的字典:
dict_users = {
"user1": ["item1", "item2", "item3", "item1", "item2", "elem3", "thing4", "thing5", "thing6"],
"user2": ["elem5", "elem8", "elem2", "elem3", "elem8", "elem5", "thing7", "thing1", "thing9"],
"user3": ["thing9", "thing7", "thing1", "thing4", "elem3", "elem9", "thing3", "thing5", "thing2"],
}
现在从这里开始,我想构建一个新字典,将用户与列表中使用最多的项目结合起来,因此在这种情况下,示例的输出将是:
dict_counted = {
'user1': 'item'
'user2': 'elem'
'user3': 'thing'
}
我现在有这样的事情:
users = ['user1', 'user2', 'user3']
dictOfRatios = dict.fromkeys(users)
for key, value in dict_users.items():
for value in dict_sers[key]:
if value.startswith("item"):
itemlist = list(value)
for user in dictOfRatios:
dictOfRatios[user] = len(itemlist)
print(dictOfRatios)
但是输出并不如预期,它甚至给出了错误的数字......在这种情况下,匹配的标准可以是从 i、e、t 到完成 item、elem、thing 的任何内容。
解决方案
python计数器是你需要的
from collections import Counter
import re
dict_users = {
'user1': ['item1', 'item2', 'item3', 'item1', 'item2', 'elem3', 'thing4', 'thing5', 'thing6'],
'user2': ['elem5', 'elem8', 'elem2', 'elem3', 'elem8', 'elem5', 'thing7', 'thing1', 'thing9'],
'user3': ['thing9', 'thing7', 'thing1', 'thing4', 'elem3', 'elem9', 'thing3', 'thing5', 'thing2']
}
users = {user: Counter() for user in dict_users.keys()}
for us, lst in dict_users.items():
user_counter = users[us]
for el in lst:
item_name = re.split("\d",el)[0]
user_counter[item_name] += 1
dict_counted = {user: counter.most_common(1)[0][0] for user, counter in users.items()}
print(dict_counted)
输出:
{
'user1': 'item',
'user2': 'elem',
'user3': 'thing'
}
推荐阅读
- java - 在 Spring Boot 应用程序中使用 AOP 记录方法调用及其参数
- python - 如何从 Windows 中的任何目录使用 manim
- angular - brotli 压缩后部署 Angular 8 项目
- complex-event-processing - Esper / NEsper EPL 声明
- node.js - 用 nodejs 编写 .conf 文件
- google-calendar-api - Google Calendars API - 插入事件 - 通过电子邮件通知组织者
- apache-spark - Pyspark:向过滤器函数添加参数
- python - csv写双引号
- python - 有没有办法将 8 通道图像传递给 CNN 的 keras?
- javascript - 以角度发射两个组件之间的属性值