How to separate a Python list into two lists, according to some aspect of the elements

后端 未结 8 709
小鲜肉
小鲜肉 2021-01-06 05:23

I have a list like this:

[[8, \"Plot\", \"Sunday\"], [1, \"unPlot\", \"Monday\"], [12, \"Plot\", \"Monday\"], [10, \"Plot\", \"Tuesday\"], [4, \"unPlot\", \"         


        
8条回答
  •  花落未央
    2021-01-06 05:43

    I have a helper function for the general case of partitioning a list in two:

    def partition(iterable, condition):
            def partition_element(partitions, element):
                (partitions[0] if condition(element) else partitions[1]).append(element)
                return partitions
            return reduce(partition_element, iterable, ([], []))
    

    For example:

    >>> partition([1, 2, 3, 4], lambda d: d % 2 == 0)
    ([2, 4], [1, 3])
    

    Or in your case:

    >>> partition(your_list, lambda i: i[1] == "Plot")
    

提交回复
热议问题