简体   繁体   中英

Python PULP sorting results

I am using PULP for linear optimization reasons. Everything works fine and I am getting results and I am printing each of them:

for i in range (0, len(opt_P)):
    print (opt_P[i].name + " = " + str(opt_P[i].varValue))

output looks like this:

0 = 20.0
1 = 20.0
10 = 1200.0
11 = 1200.0
2 = 20.0
3 = 20.0
4 = 20.0
5 = 20.0
6 = 1200.0
7 = 1200.0
8 = 45.895992
9 = 1200.0

I want to sort the results with opt_P.sort() function, but I am getting error:

'<' not supported between instances of 'LpVariable' and 'LpVariable'

Also I tried this opt_P.sort(key=lambda s: s[1]) and this one also: opt_P.sort(key=lambda s: s["name"]) but getting error:

'LpVariable' object is not subscriptable

Could you please support me in solving this issue?

You can specify the key function to be used.

Example:

>>> vars_list
[x_2, x_3, x_0, x_1, x_9, x_8, x_6, x_4, x_7, x_5]
>>> vars_list.sort(key=lambda x:x.name)
>>> vars_list
[x_0, x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9]

or if you want to sort them as integers

>>> vars_list.sort(key=lambda x:int(x.name))

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