Ped*_*gan 2 python sorting pyqt operator-keyword
我有数据行,并希望如下所示:
1
1a
1a2
2
3
9
9.9
10
10a
11
100
100ab
ab
aB
AB
Run Code Online (Sandbox Code Playgroud)
当我使用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
Run Code Online (Sandbox Code Playgroud)
这可能对你有所帮助.编辑正则表达式以匹配您感兴趣的数字模式.我将处理包含.浮点数的任何数字字段.用于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)
Run Code Online (Sandbox Code Playgroud)
输出:
1
1a
1a2
2
3
9
9.9
10
10a
11
100
100ab
ab
aB
AB
Run Code Online (Sandbox Code Playgroud)
更新 :(对评论的回应)如果你有一个类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
Run Code Online (Sandbox Code Playgroud)
所以对于你的情况,你会做这样的事情:
def __lt__(self, other):
column = self.treeWidget().sortColumn()
k1 = self.text(column)
k2 = other.text(column)
return _human_key(k1) < _human_key(k2)
Run Code Online (Sandbox Code Playgroud)
其他比较运算符(__eq__,__gt__等)将以相同的方式实现.