【发布时间】:2015-11-05 00:26:10
【问题描述】:
我正在尝试按成员变量对对象列表进行排序。通过堆栈溢出,我找到了以下方法。但是, 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
请帮忙。谢谢。
【问题讨论】:
-
您到底想要什么顺序?例如,如果值是
'22'、'2x'和'3',它们的顺序应该是什么?如果您在'22'和'3'之间进行数字比较,'3'位于'22'之前,但放置'2x'会很尴尬。 -
我在上面有一个预期的结果部分。我希望列表按数字键排序,所以 1、5、8、10、15、33、65 等。我将其更改为更清晰。
-
如果您知道
key参数将始终是一个 int 或表示 int 的字符串,您可以在设置init中的键时进行显式转换,例如self.key = int(key1).这将为您提供正确的输出,但如果无法将 key 转换为 int 则会失败 -
@R Nar,并非所有键都是整数,这就是为什么我说有些键可能看起来像 D239、D97 等。
标签: python algorithm sorting data-structures