Python - 带有字母数字的人类数字,但在 pyQt 和 __lt__ 运算符中

标签 python sorting pyqt operator-keyword

<分区>

我有数据行并希望按如下方式呈现它们:

1
1a
1a2
2
3
9
9.9
10
10a
11
100
100ab
ab
aB
AB

因为我使用的是 pyQt 并且代码包含在 TreeWidgetItem 中,所以我要解决的代码是:

def __lt__(self, otherItem):
    column = self.treeWidget().sortColumn()

    #return self.text(column).toLower() < otherItem.text(column).toLower()

    orig = str(self.text(column).toLower()).rjust(20, "0")
    other = str(otherItem.text(column).toLower()).rjust(20, "0")
    return orig < other

最佳答案

这可能对您有所帮助。编辑正则表达式以匹配您感兴趣的数字模式。我的将处理任何包含 . 的数字字段。作为花车。用途 swapcase()反转你的情况,以便 'A''a' 之后排序.

更新:优化:

import re

def _human_key(key):
    parts = re.split('(\d*\.\d+|\d+)', key)
    return tuple((e.swapcase() if i % 2 == 0 else float(e))
            for i, e in enumerate(parts))

nums = ['9', 'aB', '1a2', '11', 'ab', '10', '2', '100ab', 'AB', '10a',
    '1', '1a', '100', '9.9', '3']
nums.sort(key=_human_key)

print '\n'.join(nums)

输出:

1
1a
1a2
2
3
9
9.9
10
10a
11
100
100ab
ab
aB
AB

更新:(回复评论)如果你有一个类 Foo并想实现__lt__使用 _human_key排序方案,只返回_human_key(k1) < _human_key(k2)的结果;

class Foo(object):

    def __init__(self, key):
        self.key = key

    def __lt__(self, obj):
        return _human_key(self.key) < _human_key(obj.key)

>>> Foo('ab') < Foo('AB')
True
>>> Foo('AB') < Foo('AB')
False

所以对于你的情况,你会做这样的事情:

def __lt__(self, other):
    column = self.treeWidget().sortColumn()
    k1 = self.text(column)
    k2 = other.text(column)
    return _human_key(k1) < _human_key(k2)

其他比较运算符( __eq____gt__ 等)将以相同的方式实现。

关于Python - 带有字母数字的人类数字,但在 pyQt 和 __lt__ 运算符中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5254021/

相关文章:

python - pyqt:具有透明背景的小部件

python - 如何确定pandas数据框中的切换器和双切换器

python - numpy数组内存分配

swift - 无法对数组 : "Ambiguous reference to member ' <'" 进行排序

python - 如果比较函数需要比较项目的值,如何使用 Python3 排序键?

python - 根据任何图像几何形状调整 GraphicView

python - GNU Radio 输入和输出缓冲区如何工作?

python - 如何使用nose_parameterized参数化setUp方法

arrays - 如何先按字母然后按数字组合对字符串数组进行排序?

python - 无法使用 sqlite 和 pyqt 将数据插入数据库