我有一个这样的清单:
[[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"]]
我想根据Plot和unPlot值将其分为两个列表,结果是:
Plot
unPlot
list1=[[8, "Plot", "Sunday"], [12, "Plot", "Monday"], ...] list2=[[1, "unPlot", "Monday"], [4, "unPlot", "Tuesday"], ...]
尝试基本的列表理解:
>>> [ 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']]
或者,filter如果您喜欢函数式编程,也可以:
filter
>>> 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']]
我个人发现列表理解要清晰得多。当然,这是最“ pythonic”的方式。