简体   繁体   English

我们如何按每个对象的属性值对对象列表进行排序?

[英]How can we sort list of objects by attribute value of each object?

I have a list object which looks in the debuggers as follows:我有一个列表对象,它在调试器中看起来如下:

在此处输入图片说明

As you can see, the elements of list are ordered alphabetically.如您所见,列表的元素按字母顺序排列。 That is at index 02 , it has element 10 , instead of 2 .即在索引02 ,它具有元素10 ,而不是2 Also note that each element is actually an object of type pulp.pulp.LpVariable and the number we see in list are actually value of each object's name property (as can be seen on the last list of image).另请注意,每个元素实际上是一个pulp.pulp.LpVariable类型的对象,我们在列表中看到的数字实际上是每个对象的name属性的值(如最后一个图像列表所示)。 Pulp seem to alphabetically sort its variables. Pulp 似乎按字母顺序对其变量进行排序。

I want this list numerically sorted by name of each object.我希望这个列表按每个对象的名称进行数字排序。 That is I want 2 at index 2 , 3 at index 3 and so on.那就是我想要2在索引23在索引3等等。

I tried below:我在下面试过:

>>> from pulp import *
>>> prob = LpProblem("lp", LpMinimize)
>>> dvs = {}
>>> for i in range(20):
...     dvs[i]=LpVariable(str(i))
... 
>>> prob += lpSum(dvs.values())
>>> prob.variables()
[0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9]
>>> prob.variables().sort(key=lambda x:int(x.name))
>>> prob.variables()
[0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9]

As you can see, sorting is simply not happening.如您所见,排序根本没有发生。 I expected output on the last line to be:我预计最后一行的输出是:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

How can I get this done?我怎样才能做到这一点?

I don't know what prob.variables() does but the fact that is is a callable makes me strongly suspect that you are not referring to the same list when you sort it and when you print it, but getting a new list each time you call prob.variables()我不知道prob.variables()是做什么的,但它是一个可调用的事实让我强烈怀疑您在排序和打印时不是指同一个列表,而是每次都得到一个新列表你打电话给prob.variables()

Please try the following:请尝试以下操作:

result = sorted(prob.variables(), key=lambda x:int(x.name))
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM