Python 如何使用dict.get()';具有复杂数据的默认参数

Python 如何使用dict.get()';具有复杂数据的默认参数,python,dictionary,Python,Dictionary,下面是使用dict.get()方法的默认参数计算单词的脚本: 这适用于简单的计数。但是如果我想收集更多的数据,比如word_列表中单词条目的索引,那么我需要将这些额外的数据插入get()的默认参数和尾部表达式(“+1”) 我该怎么做 for word in sorted(set(word_list)): indices = [i for i, x in enumerate(word_list) if x == word] counts = word_list.count(wor

下面是使用dict.get()方法的默认参数计算单词的脚本:

这适用于简单的计数。但是如果我想收集更多的数据,比如word_列表中单词条目的索引,那么我需要将这些额外的数据插入get()的默认参数和尾部表达式(“+1”)

我该怎么做

for word in sorted(set(word_list)):

    indices = [i for i, x in enumerate(word_list) if x == word]
    counts = word_list.count(word)

    word_data[word] = {}
    word_data[word]['count'] = counts
    word_data[word]['indexes'] = indices

希望这对你有帮助,伙计

如果您想继续使用
dict.get
方法,那么您可以这样做:

 for i, word in enumerate(word_list):
     elem = word_data.get(word, {'index':[], 'count':0})
     word_data.update({
         word: {
             'indexes': elem['indexes']+[i], 
             'count': elem['count']+1
         }
     })
因此,您将得到:

{'abc': {'count': 2, 'indexes': [0, 1]}, 'def': {'count': 1, 'indexes': [2]}}

虽然,在这种特殊情况下,仅仅跟踪索引可能更有效(因为每个单词的出现次数正好是该列表的长度),对吗?:)

你能举一个关于“更多数据”的更现实的例子吗?因为大多数人会直接使用
collections.Counter
作为您所展示的示例。
{'abc': {'count': 2, 'indexes': [0, 1]}, 'def': {'count': 1, 'indexes': [2]}}