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

后端 未结 8 703
小鲜肉
小鲜肉 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.

    0 讨论(0)
  • 2021-01-06 06:03

    You could simply go through the list, and check if the value is "Plot" like this:

    for i in List:
      if i[1]=="Plot":
        list1.append(i)
      else:
        list2.append(i)
    
    0 讨论(0)
提交回复
热议问题