我是 python 的新手,我有一个关于在不敏感的情况下计算列表中元素的问题。例如,我有一个列表如下:
ActorContext
我想要的字典应该是这样的:
My_list = ['modulus of elasticity', 'NIRS', 'mechanical properties', 'Modulus of elasticity', 'NIRS', 'mechanical properties']
实际上我知道如何以正常方式计算它们,但是像:弹性模量和弹性模量这样的词将被视为不同的元素。请注意:我想保留 NIRS 以保留大写字母。我想知道是否有办法在 python 中处理这个敏感案例。任何帮助都感激不尽。谢谢!
答案 0 :(得分:2)
from collections import Counter
orig = Counter(My_list)
lower = Counter(map(str.lower, My_list))
desired = {}
for k_orig in orig:
k_lower = k_orig.lower()
if lower[k_lower] == orig[k_orig]:
desired[k_orig] = orig[k_orig]
else:
desired[k_lower] = lower[k_lower]
desired
# {'modulus of elasticity': 2, 'NIRS': 2, 'mechanical properties': 2}