Append to a dict of lists with a dict comprehension

前端 未结 4 1219
你的背包
你的背包 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:09

    I'd use filter:

    >>> words = ['abcd', 'abdef', 'eft', 'egg', 'uck', 'ice']
    >>> index = {k.lower() : list(filter(lambda x:x[0].lower() == k.lower(),words)) for k in 'aeiou'}
    >>> index
    {'a': ['abcd', 'abdef'], 'i': ['ice'], 'e': ['eft', 'egg'], 'u': ['uck'], 'o': []}
    

提交回复
热议问题