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

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

    You could use list comprehensions, e.g.

    # old_list elements should be tuples if they're fixed-size, BTW
    list1 = [(X, Y, Z) for X, Y, Z in old_list if Y == 'Plot']
    list2 = [(X, Y, Z) for X, Y, Z in old_list if Y == 'unPlot']
    

    If you want to traverse the input list only once, then maybe:

    def split_list(old_list):
        list1 = []
        list2 = []
        for X, Y, Z in old_list:
            if Y == 'Plot':
                list1.append((X, Y, Z))
            else:
                list2.append((X, Y, Z))
        return list1, list2
    

提交回复
热议问题