Append to a dict of lists with a dict comprehension

前端 未结 4 1208
你的背包
你的背包 2021-02-20 05:20

Suppose I have a large list of words. For an example:

>>> with open(\'/usr/share/dict/words\') as f:
...     words=[word for word in f.read().split(\'\\         


        
4条回答
  •  孤独总比滥情好
    2021-02-20 06:06

    This is not exactly a dict comprehension, but:

    reduce(lambda d, w: d.setdefault(w[0], []).append(w[1]) or d,
           ((w[0].lower(), w) for w in words
            if w[0].lower() in 'aeiou'), {})
    

提交回复
热议问题