python - 仅将列表中的多个相似项目替换为 1
问题描述
我正在使用一个列表,该列表包含基于脚本中出现的字符名称列表,但其中一些具有多个别名,只是略有不同。我想要做的是能够计算角色出现在脚本中的次数。
my_dict = {i:new_list.count(i) for i in new_list}
print(my_dict)
{'NICK FURY': 110, 'AGENT PHIL COULSON': 48, 'AGENT MARIA HILL': 24, 'SELVIG': 15, 'CLINT BARTON': 23, 'LOKI': 72, 'NATASHA': 73, 'BANNER': 79, 'STEVE (V.O.)': 2, 'STEVE': 74, 'TONY': 130, 'JARVIS': 11, 'CAPTAIN AMERICA': 39, 'IRON MAN': 23, 'NICK FURY (V.O.)': 6, 'THOR': 50, 'LOKI (V.O.)': 2, 'TONY (V.O.)': 1, 'CAPTAIN AMERICA (V.O.)': 3, 'BLACK WIDOW (V.O.)': 2, 'HAWKEYE': 10, 'BLACK WIDOW': 18, 'IRON MAN (V.O.)': 4, 'HAWKEYE (V.O.)': 1, 'HULK': 1}
上面的代码计算列表中每个元素的出现次数。但正如您所看到的,它将“IRON MAN”与“TONY”分开处理,并将脚本的“(VO)”方面分开。我找到了一种替换所有这些的方法,但它很长。
new_list[:] = [s.replace('NICK FURY (V.O.)', 'NICK FURY') for s in new_list]
new_list[:] = [s.replace('STEVE (V.O.)', 'STEVE') for s in new_list]
new_list[:] = [s.replace('LOKI (V.O.)', 'LOKI') for s in new_list]
new_list[:] = [s.replace('BLACK WIDOW (V.O.)', 'NATASHA') for s in new_list]
new_list[:] = [s.replace('BLACK WIDOW', 'NATASHA') for s in new_list]
new_list[:] = [s.replace('TONY (V.O.)', 'TONY') for s in new_list]
new_list[:] = [s.replace('IRON MAN', 'TONY') for s in new_list]
new_list[:] = [s.replace('IRON MAN (V.O.)', 'TONY') for s in new_list]
new_list[:] = [s.replace('CAPTAIN AMERICA', 'STEVE') for s in new_list]
new_list[:] = [s.replace('HAWKEYE (V.O.)', 'CLINT BARTON') for s in new_list]
new_list[:] = [s.replace('HAWKEYE', 'CLINT BARTON') for s in new_list]
new_list[:] = [s.replace('HULK', 'BANNER') for s in new_list]
这确实给了我想要的输出,即:
my_dict = {i:new_list.count(i) for i in new_list}
print(my_dict)
{'NICK FURY': 116, 'AGENT PHIL COULSON': 48, 'AGENT MARIA HILL': 24, 'SELVIG': 15, 'CLINT BARTON': 34, 'LOKI': 74, 'NATASHA': 93, 'BANNER': 80, 'STEVE': 118, 'TONY': 158, 'JARVIS': 11, 'THOR': 50}
但是有没有更好的方法来做到这一点?
解决方案
推荐阅读
- python - XGB 性能优于神经网络
- tfs - Git tfs clone - 服务器无法处理请求。---> 生成 XML 文档时出错。---> 指定的强制转换无效
- java - 不使用 android studio 和 ms sql 数据库在 android 应用程序中显示图像
- reactjs - 链接按钮的材质 UI 图标不起作用
- sorting - dart - 对期货列表进行排序
- javascript - 科尔多瓦地理定位不准确
- c# - 从 .trx 文件中提取代码覆盖率报告
- java - 如何将 mysql Query 包括 join 更改为不使用 join?
- c# - Asp.net core 3. 在 IIS 中托管应用程序和并行开发的问题
- python - 如何使jpg图像半透明?