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

后端 未结 8 701
小鲜肉
小鲜肉 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:57

    Try with basic list comprehension:

    >>> [ x for x in l if x[1] == "Plot" ]
    [[8, 'Plot', 'Sunday'], [12, 'Plot', 'Monday'], [10, 'Plot', 'Tuesday'], [14, 'Plot', 'Wednesday'], [19, 'Plot', 'Thursday'], [28, 'Plot', 'Friday']]
    >>> [ x for x in l if x[1] == "unPlot" ]
    [[1, 'unPlot', 'Monday'], [4, 'unPlot', 'Tuesday'], [6, 'unPlot', 'Wednesday'], [1, 'unPlot', 'Thursday'], [10, 'unPlot', 'Friday'], [3, 'unPlot', 'Saturday']]
    

    Or with filter if you fancy functional programming:

    >>> filter(lambda x: x[1] == "Plot", l)
    [[8, 'Plot', 'Sunday'], [12, 'Plot', 'Monday'], [10, 'Plot', 'Tuesday'], [14, 'Plot', 'Wednesday'], [19, 'Plot', 'Thursday'], [28, 'Plot', 'Friday']]
    >>> filter(lambda x: x[1] == "unPlot", l)
    [[1, 'unPlot', 'Monday'], [4, 'unPlot', 'Tuesday'], [6, 'unPlot', 'Wednesday'], [1, 'unPlot', 'Thursday'], [10, 'unPlot', 'Friday'], [3, 'unPlot', 'Saturday']]
    

    I personally find list comprehensions much clearer. It's certainly the most "pythonic" way.

提交回复
热议问题