python判断lt中是否包含数字0,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

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

解决方案

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'.

Updated: Refined:

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)

Output:

1

1a

1a2

2

3

9

9.9

10

10a

11

100

100ab

ab

aB

AB

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)

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值