[英]Comparing the second element of two tuples with '<' fails in Python
I'm trying to write a merge-sort function that takes a list and a comparison function, in Python: 我正在尝试在Python中编写一个包含列表和比较函数的合并排序函数:
def sort(unsorted, comp_func=lambda x, y: x < y):
length = len(unsorted)
if length <= 1: return unsorted
halflen = length / 2
lsorted= sort(unsorted[:halflen])
rsorted = sort(unsorted[halflen:])
combined = []
while True:
if len(lsorted) > 0:
if len(rsorted) > 0 and comp_func(rsorted[0], lsorted[0]):
combined.append(rsorted[0])
rsorted = rsorted[1:]
else:
combined.append(lsorted[0])
lsorted = lsorted[1:]
elif len(rsorted) > 0:
combined.append(rsorted[0])
rsorted = rsorted[1:]
else:
break
return combined
It works fine with lists of int (with the default comp_func), as well as lists of tuples that have 2 int when the comparison function compares the first element of such a tuple. 当比较函数比较该元组的第一个元素时,它可以很好地与int列表(默认为comp_func)以及具有2 int的元组列表一起使用。
comp_func = lambda x, y: x[0] < y[0]
But when I write the comparison function to compare by the second element of the tuple, the list returned is still the unsorted version. 但是,当我编写比较函数以通过元组的第二个元素进行比较时,返回的列表仍然是未排序的版本。
comp_func = lambda x, y: x[1] < y[1]
However, if I change the '<' operator to '>' so that the list is to be sorted decrementally, it works: 但是,如果我将'<'运算符更改为'>',以便对列表进行递减排序,那么它将起作用:
comp_func = lambda x, y: x[1] > y[1]
Don't know why '<' fails on the second element of the tuples... 不知道为什么'<'在元组的第二个元素上失败...
Having searched for a possible explanation, I found this: Does python think 10 is less than 9 . 搜索了可能的解释后,我发现了这一点: python是否认为10小于9 。 However, that is not the case; 但是,事实并非如此。 the list being sorted contain tuples of int , not string . 被排序的列表包含int的元组,而不是string 。
You don't actually show a transcript of how you changed the operator, so this is just a guess, but notice that these two lines 您实际上并未显示有关如何更改运算符的记录,因此这只是一个猜测,但是请注意,这两行
lsorted= sort(unsorted[:halflen])
rsorted = sort(unsorted[halflen:])
don't pass comp_func. 不要通过comp_func。 So if you did something like this: 因此,如果您执行以下操作:
>>> sort([(3,4),(1,2), (2,3)])
[(1, 2), (2, 3), (3, 4)]
>>> sort([(3,4),(1,2), (2,3)],lambda x,y: x[1] > y[1])
[(3, 4), (1, 2), (2, 3)]
you would get inconsistent results because half the time it's sorting with a different comp_func. 您会得到不一致的结果,因为一半的时间是使用不同的comp_func进行排序。 Passing comp_func in the lsorted=
and rsorted=
lines fixes this: 在lsorted=
和rsorted=
行中传递comp_func可以解决此问题:
>>> sort([(3,4),(1,2), (2,3)],lambda x,y: x[1] > y[1])
[(3, 4), (2, 3), (1, 2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.