Python-人类排序的数字,带有字母数字,但使用pyQt和__lt__运算符 [英] Python - Human sort of numbers with alpha numeric, but in pyQt and a __lt__ operator

查看:90
本文介绍了Python-人类排序的数字,带有字母数字,但使用pyQt和__lt__运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据行,并希望将它们显示如下:

I have data rows and wish to have them presented as follows:

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

当我使用pyQt并且代码包含在TreeWidgetItem中时,我要解决的代码是:

As I am using pyQt and code is contained within a TreeWidgetItem, the code I'm trying to solve is:

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

推荐答案

这可能会对您有所帮助.编辑正则表达式以匹配您感兴趣的数字模式.Mine会将包含.的所有数字字段都视为浮点数.使用swapcase()反转大小写,以便'A''a'之后排序.

This may help you. Edit the regexp to match the digit patterns you're interested in. Mine will treat any digit fields containing . as floats. Uses swapcase() to invert your case so that 'A' sorts after '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,并且想要使用_human_key排序方案实现__lt__,则只需返回_human_key(k1) < _human_key(k2)的结果;

Update: (response to comment) If you have a class Foo and want to implement __lt__ using the _human_key sorting scheme, just return the result of _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

因此,对于您的情况,您将执行以下操作:

So for your case, you'd do something like this:

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__等)将以相同的方式实现.

The other comparison operators (__eq__, __gt__, etc) would be implemented in the same way.

这篇关于Python-人类排序的数字,带有字母数字,但使用pyQt和__lt__运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆