简体   繁体   English

根据另一个列表排序对对象列表进行排序

[英]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.我一直在寻找一种基于另一个 int 列表的排序顺序对对象进行排序的方法,但我还没有找到。

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.我认为问题出在“sorted(zip(listOfInt, listOfObjects))”部分,但我不知道如何解决这个问题,或者是否有其他方法可以解决。

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] . zipList[int]List[Object]的应用在这里返回一个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). sortedkey允许您定义相对于列表中元素的排序键(在这种情况下,取整数)。 list 's sort method supports the same argument ( here's the documentation ). listsort方法支持相同的参数(这里是文档)。 The outer comprehension fetches the element of the tuple you care about (the Object ) post-sort.外部理解在排序后获取您关心的元组的元素( Object )。 Given what you want is to sort List[Object] along the list of integers, this should work.鉴于您想要的是沿整数列表对List[Object]进行排序,这应该可以工作。

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.就是如果你指定key ,这里的比较在Tuple[int, Object]之间。 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).比较每个元组时,先比较int ,如果int不能确定结果,比较Object (所以Object必须支持比较方法)。

Normally, your approach would be fine if listOfInts did not contain duplicates.通常,如果listOfInts不包含重复项,您的方法会很好。 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)))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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