Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I have a list like this:

[[8, "Plot", "Sunday"], [1, "unPlot", "Monday"], [12, "Plot", "Monday"], [10, "Plot", "Tuesday"], [4, "unPlot", "Tuesday"], [14, "Plot", "Wednesday"], [6, "unPlot", "Wednesday"], [1, "unPlot", "Thursday"], [19, "Plot", "Thursday"], [28, "Plot", "Friday"], [10, "unPlot", "Friday"], [3, "unPlot", "Saturday"]]

I want to separate it into two lists according the Plot and unPlot values, resulting:

list1=[[8, "Plot", "Sunday"], [12, "Plot", "Monday"], ...]
list2=[[1, "unPlot", "Monday"], [4, "unPlot", "Tuesday"], ...]
like image 689
saun jean Avatar asked Nov 29 '22 03:11

saun jean


1 Answers

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.

like image 142
Chewie Avatar answered Dec 21 '22 21:12

Chewie