Python:元组项列表中的总和项是否包含区分大小写的键?

Python:元组项列表中的总和项是否包含区分大小写的键?,python,list,tuples,Python,List,Tuples,我有一个包含哈希标记和频率的元组列表,例如: [('#Example', 92002), ('#example', 65544)] 我想对与元组中的第一个条目具有相同字符串的条目进行求和(但区分大小写的版本不同),使第一个条目在第二个条目中保持最大值。上述内容将转化为: [('#Example', 157,546)] 到目前为止,我已经试过了: import operator for hashtag in hashtag_freq_list: if hashtag[0].lowe

我有一个包含哈希标记和频率的元组列表,例如:

[('#Example', 92002),
 ('#example', 65544)]
我想对与元组中的第一个条目具有相同字符串的条目进行求和(但区分大小写的版本不同),使第一个条目在第二个条目中保持最大值。上述内容将转化为:

[('#Example', 157,546)]
到目前为止,我已经试过了:

import operator

for hashtag in hashtag_freq_list:
    if hashtag[0].lower() not in [res_entry[0].lower() for res_entry in res]:
        entries = [entry for entry in hashtag_freq_list if hashtag[0].lower() == entry[0].lower()]
        k = max(entries,key=operator.itemgetter(1))[0]  
        v = sum([entry[1] for entry in entries])
        res.append((k,v))
我只是想知道是否可以用一种更优雅的方式来处理这个问题?

我会使用字典

data = [('#example', 65544),('#Example', 92002)]

hashtable = {}

for i in data:

    # See if this thing exists regardless of casing
    if i[0].lower() not in hashtable:

        # Create a dictionary
        hashtable[i[0].lower()] = {
            'meta':'',
            'value':[]
        }

        # Copy the relevant information
        hashtable[i[0].lower()]['value'].append(i[1])
        hashtable[i[0].lower()]['meta'] = i[0]

    # If the value exists
    else:

        # Check if the number it holds is the max against 
        # what was collected so far. If so, change meta
        if i[1] > max(hashtable[i[0].lower()]['value']):
            hashtable[i[0].lower()]['meta'] = i[0]

        # Append the value regardless
        hashtable[i[0].lower()]['value'].append(i[1])

# For output purposes
myList = []

# Build the tuples
for node in hashtable:
    myList.append((hashtable[node]['meta'],sum(hashtable[node]['value'])))

# Voila!
print myList
# [('#Example', 157546)]

因此,它不是一个代码编写服务。请展示您自己解决问题的尝试(如果您无法让它工作)。抱歉,伙计们,完全正确。您关心保留哪一个大写字母吗?@haavee理想情况下,在使用最大频率时,这是否始终保持最大值为
meta
?反转输入(
data=[('example',65544),('example',92002)]
)将给出:
[('example',157546)]
@jfixed。让我知道你认为什么看起来好多了。我原本认为这是一个更为琐碎的问题。最近,我一直在大量使用的内置功能Pandas@jfive从头开始编写代码总是比较容易:D而且它解决问题的速度要快得多;)