简体   繁体   中英

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 . 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 seem to alphabetically sort its variables.

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.

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()

Please try the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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