Python - Human sort of numbers with alpha numeric, but in pyQt and a __lt__ operator(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
推荐答案
这可能对您有所帮助.编辑正则表达式以匹配您感兴趣的数字模式.我的会将任何包含 .
的数字字段视为浮点数.使用 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 '
'.join(nums)
输出:
1
1a
1a2
2
3
9
9.9
10
10a
11
100
100ab
ab
aB
AB
更新:(对评论的回应)如果您有一个 Foo
类并且想要使用 _human_key
实现 __lt__
code>排序方案,只返回_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__ 运算符中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!