Python: split a list based on a condition?

前端 未结 30 1886
误落风尘
误落风尘 2020-11-22 06:56

What\'s the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:

30条回答
  •  悲&欢浪女
    2020-11-22 07:17

    I basically like Anders' approach as it is very general. Here's a version that puts the categorizer first (to match filter syntax) and uses a defaultdict (assumed imported).

    def categorize(func, seq):
        """Return mapping from categories to lists
        of categorized items.
        """
        d = defaultdict(list)
        for item in seq:
            d[func(item)].append(item)
        return d
    

提交回复
热议问题