我是python的新手,我有一个关于在不敏感的情况下在列表中计数元素的问题。例如,我有如下列表:
My_list = ['modulus of elasticity', 'NIRS', 'mechanical properties', 'Modulus of elasticity', 'NIRS', 'mechanical properties']我想要的字典应该是这样的:
Desired_dictionary = {'modulus of elasticity': 2, 'NIRS': 2, 'mechanical properties': 2}实际上,我知道如何用正常的方法来计算它们,但是像:,弹性模量,和,弹性模量,将作为不同的元素来计算。注意:我想保留NIRS的大写字母。我想知道在python中是否有一种处理这种敏感情况的方法。任何帮助都将不胜感激。谢谢!
发布于 2021-01-30 16:18:49
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}https://stackoverflow.com/questions/65970199
复制相似问题