python - 在 Python 中将两个元组的第二个元素与 '<' 进行比较失败

标签 python lambda

我正在尝试用 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

当比较函数比较这样的元组。

comp_func = lambda x, y: x[0] < y[0]

但是当我编写比较函数来比较元组的第二个元素时,返回的列表仍然是未排序的版本。

comp_func = lambda x, y: x[1] < y[1]

但是,如果我将“<”运算符更改为“>”以便列表按递减方式排序,它会起作用:

comp_func = lambda x, y: x[1] > y[1]

不知道为什么 '<' 在元组的第二个元素上失败......

在寻找可能的解释后,我发现了这个:Does python think 10 is less than 9 .然而,事实并非如此;正在排序的列表包含 int 的元组,而不是 string

最佳答案

您实际上并没有显示您如何更改运算符的记录,所以这只是一个猜测,但请注意这两行

lsorted= sort(unsorted[:halflen])
rsorted = sort(unsorted[halflen:])

不要传递 comp_func。所以如果你做了这样的事情:

>>> 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)]

您会得到不一致的结果,因为有一半时间它使用不同的 comp_func 进行排序。在 lsorted=rsorted= 行中传递 comp_func 解决了这个问题:

>>> sort([(3,4),(1,2), (2,3)],lambda x,y: x[1] > y[1])
[(3, 4), (2, 3), (1, 2)]

关于python - 在 Python 中将两个元组的第二个元素与 '<' 进行比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9866222/

相关文章:

python - 如何在 PyQt 的 QTableWidget 中的同一单元格中显示图像和文本?

node.js - 升级到 AnonymousTraversalSource (Gremlin 3.3.5+ Node.js)

java - 在 Java 8 中使用 lambda 表达式有什么优点?

vb.net - 合并两个 XElement

java - HotSpot 中 Runnable 的成本

python - 合并或加入 numpy 数组

python - AttributeError: 'MLPClassifier' 对象没有属性 'best_loss_'

python - 使用 Python 将命令参数发送到串口

python - 使用Python查看表是否存在

java - 如何在我想要返回的方法中从 lambda 返回值?