需要根据特定条件删除大量元素:
[[1, 4, 5], [1, 3, 4], [1, 2, 3]]
以上所有列表都被认为是重复的,因为它们的第一个元素是相等的。第三个列表需要保留,因为它的第二个元素是最小的。注意,实际的列表列表有超过400万个元素,是双重排序的,需要保留排序。在
首先根据内部列表的第二个元素对列表进行排序,并按倒序(降序)排序,然后根据第一个元素按正常(升序)顺序排序:
sorted(sorted(the_list, key=itemgetter(1), reverse=True), key=itemgetter(0))
三个实际排序的重复列表示例:
^{pr2}$目标是准备列表以进行对分搜索。有人能告诉我如何使用Python实现这一点吗?在
可以使用dict对元素进行分组,始终使用较小的第二个元素保留子列表:
也可以将两个键传递给sorted,不需要调用sorted两次:
^{pr2}$如果您想按照维护dict中的顺序,则需要保留顺序。:
^{3}$但不确定这是否合适,因为你在排序之后的数据,所以你会失去任何顺序。在
您可能会发现非常有用的是sortedcontainers.sorteddict:
它有您想要的所有方法bisect,bisect_left等。。在
如果我没弄错,解决方法可能是这样的:
所以在
newlist
中,我们将收到[[1, 2, 3], [7, 1, 8]]
的简化列表。在相关问题 更多 >
编程相关推荐