gpt4 book ai didi

python - 按成员变量正确排序列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:43:14 24 4
gpt4 key购买 nike

我正在尝试按成员变量对对象列表进行排序。通过堆栈溢出,我找到了以下方法。但是,lsort 逐位比较,因此 5、3、7、21、64 将排序为 21、3、5、64、7(我希望这是数字:3、5 , 7, 21, 64).我不确定如何解决这个问题,因为有些键可能看起来像 D239、D97、D11(lsort 看起来像 D11、D239、D97;我希望它看起来像 D11、D97 , D239).虽然我更喜欢一种方法,但我想两种方法也可以。

import operator 

class foo:
def __init__(self, key1, data1, data2):
#all of these values are strings, even though some may be ints
self.key = key1
self.d1 = data1
self.d2 = data2

#sorts list l by member variable search
def lsort (l, search):
#this doesn't actually work very well.
#key can be int or string
#when key is an int, this seems to order by number of digits, then low to high
#(e.g. 11, 12, 40, 99, 3, 6, 8)
return sorted(l, key=operator.attrgetter(search))


l1 = [foo('12', 'foo1', None), foo('8', 'qwer', None), foo('7', 'foo3', None), foo('13', 'foo2', None), foo('77', 'foo4', None), foo('12', 'foo5', None) ]


for item in lsort(l1, 'key'):
print item.key, item.d1, item.d2

输出:

12 foo1 None 
12 foo5 None
13 foo2 None
7 foo3 None
77 foo4 None
8 qwer None

预期:

7 foo3 None
8 qwer None
12 foo1 None
12 foo5 None
13 foo2 None
77 foo4 None

为什么会这样?我使用相同的排序并在一个非常基础的类上运行它,它似乎工作正常。

class foo:
def __init__(self, d1):
self.bar= d1

请协助。谢谢。

最佳答案

啊,是的。老话,“顺其自然吧!”问题。

翻译我从 Tye McQueen 那里用 Perl 得到的一个老 hack,像这样的东西应该适用于字符串:

import re

def replace_match(match):
value = match.group(0)
if value[0] == ".":
return value
else:
return ("0"*(9-len(value))) + value

def replace_with_natural(string):
return re.sub("(\.\d*|[1-9]\d{0,8})", replace_match, string)

items = ["hello1", "hello12", "foo12.1", "foo12.05", "hello3", "foo.12.12"]
print(sorted(items, key=replace_with_natural))

我们的想法是,我们用固定长度的数字替换字符串中的每个数字,这些数字按我们喜欢的方式按字典顺序排序。

请注意,像这样的任何函数都会遇到它处理不当的问题。在这种情况下,科学计数法处理不当。但这将在 99.99% 的时间内完成人们对嵌入数字的期望。

关于python - 按成员变量正确排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33534617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com