在python中,在列表中使用不区分大小写的方式计算相同的元素

2024-06-01 11:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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中处理这个敏感的案例。任何帮助都将不胜感激。谢谢


Tags: of元素列表字典mypropertieslist区分
1条回答
网友
1楼 · 发布于 2024-06-01 11:59:22

使用^{}

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}

相关问题 更多 >