Sorting list based on values from another list?

后端 未结 15 2634
温柔的废话
温柔的废话 2020-11-21 07:14

I have a list of strings like this:

X = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\"]
Y = [ 0,   1,   1,   0,   1,   2,   2,   0,   1 ]
         


        
15条回答
  •  生来不讨喜
    2020-11-21 08:11

    I have created a more general function, that sorts more than two lists based on another one, inspired by @Whatang's answer.

    def parallel_sort(*lists):
        """
        Sorts the given lists, based on the first one.
        :param lists: lists to be sorted
    
        :return: a tuple containing the sorted lists
        """
    
        # Create the initially empty lists to later store the sorted items
        sorted_lists = tuple([] for _ in range(len(lists)))
    
        # Unpack the lists, sort them, zip them and iterate over them
        for t in sorted(zip(*lists)):
            # list items are now sorted based on the first list
            for i, item in enumerate(t):    # for each item...
                sorted_lists[i].append(item)  # ...store it in the appropriate list
    
        return sorted_lists
    

提交回复
热议问题