简体   繁体   中英

Sort a list of Objects based on another list sort

I've been looking for hours a way to sort objects based on the sorting order of another list of int but I haven't found.

I've tried

newList = [element for _,element in sorted(zip(listOfInt, listOfObjects))]

but it displays the following error:

"'<' not supported between instances of 'Object' and 'Object'"

I think the problem is in the "sorted(zip(listOfInt, listOfObjects))" part but I have no idea how to fix this or if there is another way to do it.

You could write it like so:

newList = [
    elem[1]
    for elem in sorted(zip(listOfInt, listOfObjects), key=lambda tup: tup[0])
]

The application of zip to List[int] and List[Object] here returns a sequence of Tuple[int, Object] . sorted 's key allows you to define the sort key relative to elements in the list (in this case, taking the integer). list 's sort method supports the same argument ( here's the documentation ). The outer comprehension fetches the element of the tuple you care about (the Object ) post-sort. Given what you want is to sort List[Object] along the list of integers, this should work.

The reason for this error:

'<' not supported between instances of 'Object' and 'Object'

is that if you don't specify key , the comparison here's between Tuple[int, Object] s. When each tuple is compared, the int s will be compared first, and then the Object s will be compared if the int s can't determine the outcome (so the Object must support a comparison method).

Normally, your approach would be fine if listOfInts did not contain duplicates. Lists and tuples are compared lexicographically, so when there is a duplicate, the second element in each tuple gets compared. To prevent this from happening, you can insert an element into the key before the incomparable objects:

newList = [element for _, (_, element) in sorted(zip(listOfInt, enumerate(listOfObjects)))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM