Simple way to group items into buckets

后端 未结 5 823
耶瑟儿~
耶瑟儿~ 2020-12-29 08:48

I often want to bucket an unordered collection in python. itertools.groubpy does the right sort of thing but almost always requires massaging to sort the items first and cat

5条回答
  •  攒了一身酷
    2020-12-29 09:34

    Edit:

    Using DSM's answer as a start, here is a slightly more concise, general answer:

    d = defaultdict(list)
    map(lambda x: d[x in 'aeiou'].append(x),'thequickbrownfoxjumpsoverthelazydog')
    

    or

    d = defaultdict(list)
    map(lambda x: d[x %10].append(x),xrange(21))
    
    #

    Here is a two liner:

    d = {False:[],True:[]}
    filter(lambda x: d[True].append(x) if x in 'aeiou' else d[False].append(x),"thequickbrownfoxjumpedoverthelazydogs")
    

    Which can of course be made a one-liner:

    d = {False:[],True:[]};filter(lambda x: d[True].append(x) if x in 'aeiou' else d[False].append(x),"thequickbrownfoxjumpedoverthelazydogs")
    

提交回复
热议问题