首页 > 解决方案 > 仅将列表中的多个相似项目替换为 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

解决方案


推荐阅读