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__ 运算符中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 带有字母数字的人类数字,但在 pyQt 和
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
