Simple way to group items into buckets

后端 未结 5 839
耶瑟儿~
耶瑟儿~ 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:32

    Here is a simple two liner

    d = {}
    for x in "thequickbrownfoxjumpsoverthelazydog": d.setdefault(x in 'aeiou', []).append(x)
    

    Edit:

    Just adding your other case for completeness.

    d={}
    for x in xrange(21): d.setdefault(x%10, []).append(x)
    

提交回复
热议问题