Skip to main content
 首页 » 编程设计

python之构建元组列表的程序

2025年01月19日13mfrbuaa

我正在尝试编写一个程序,它接受一个频率字典和一个整数,并返回一个元组列表,其中包含出现次数超过 min_times 的所有单词。

def words_often(freqs, min_times): 
tuple_list = [] 
for key in freqs: 
    word_list = [] 
    if freqs[key] > min_times: 
        store_value = freqs[key] 
        for key2 in freqs: 
            if freqs[key2] == store_value: 
                word_list += [key2] 
    if freqs[key] not in tuple_list: 
        tuple_list += [(word_list, store_value)] 
return tuple_list 
 
 
#test program 
freqs = {'yeah':15, 'one': 1, 'crazy': 3, 'lonely': 1} 
 
print(words_often(freqs, 0)) 

但是有些问题,上面测试的返回值是:

[([‘yeah’], 15), ([‘one’, ‘lonely’], 1), ([‘crazy’], 3), ([‘one’, ‘lonely’], 1)] 

这个返回值不应该有最后一个条目,因为它是重复的。

我怎样才能使我的代码更简单,因为很多事情正在发生,我无法确定问题所在。

编辑:我需要将元组中的单词分组到列表中。例如,第一个条目应该是 (['yeah'], 15) 并且对于具有相同值的词(一个和孤独),我需要将它们分组为 (['one', 'lonely'], 1)

请您参考如下方法:

因为你想按值对键进行分组,你可以使用 itertools.groupby :

from itertools import groupby 
data = {'yeah':15, 'one': 4, 'crazy': 3, 'lonely': 4} 
min_times = 3 
 
get_value = lambda kv: kv[1] 
sorted_data = sorted(data.items(), key= get_value, reverse=True) 
print(sorted_data) 
# [('yeah', 15), ('one', 4), ('lonely', 4), ('crazy', 3)] 
 
 
print([([v[0] for v in vs], k) for k,vs in groupby(sorted_data, key= get_value) if k > min_times]) 
# [(['yeah'], 15), (['one', 'lonely'], 4)]