如何基于值从列表中选择实例?

时间:2019-01-29 08:56:20

标签: python list class

我有一个包含两个变量的类的实例列表:值和期望。

import random 

class MyClass:
    def __init__(self, value):
        self.value = value
        self.expectation = random.random()

my_list = []
for i in range(1, 11):
    my_list.append(MyClass(i))

我现在想获得具有最大期望值的实例的值。我怎么得到这个?

3 个答案:

答案 0 :(得分:3)

Oneliner:

<th>
   <h3>Example Form</h3>This project taught me how to build a form 
   that you can put into a website for someone to fill out.<br />
   <form method="get" action="projects/IlanTretiak1.5-Forms.html">
   <button type="submit"> Download </button>
   </form>
   <form action="projects/IlanTretiak1.5-Forms.html">
   <button formtarget="_blank"> Visit </button>
   </form>
</th> 

答案 1 :(得分:1)

my_list = []
max_obj = max(my_list,key=lambda myClass:myclass.expectation)
max_value = max_obj.value

答案 2 :(得分:0)

最大期望:

{"entries":
      [{
         ".tag":"deleted",
         "name":"contract test category 0",
         "id":"id:zN8VXp5DPoAAAAAAAAABJw",
         "path_lower":"/contract/contract test category 0",
         "path_display":"/contract/contract test category 0"
       },
       {
         ".tag":"deleted",
         "name":"test.png",
         "path_lower":"/contract/contract test category 1/contract test sub category 1/test.png",
         "path_display":"/contract/contract test category 1/contract test sub category 1/test.png"
       },
       {
         ".tag":"deleted",
         "name":"contract test sub category 1",
         "path_lower":"/contract/contract test category 1/contract test sub category 1",
         "path_display":"/contract/contract test category 1/contract test sub category 1"
       },
       {
         ".tag":"deleted",
         "name":"contract test category 1",
         "path_lower":"/contract/contract test category 1",
         "path_display":"/contract/contract test category 1"
       },
       {
         ".tag":"folder",
         "name":"contract test sub category 1",
         "id":"id:zN8VXp5DPoAAAAAAAAABKg",
         "path_lower":"/contract/contract test category 0/contract test sub category 1",
         "path_display":"/contract/contract test category 0/contract test sub category 1"
       },
       {
         ".tag":"file",
         "name":"test.png",
         "id":"id:zN8VXp5DPoAAAAAAAAABLQ",
         "client_modified":"2019-01-25T12:30:58Z","server_modified":"2019-01-29T06:39:51Z",
         "rev":"0123a000000011c24d890",
         "size":181599,
         "path_lower":"/contract/contract test category 0/contract test sub category 1/test.png",
         "path_display":"/contract/contract test category 0/contract test sub category 1/test.png", 
        }],
     "cursor":"AAGsW7C_w_KUDSqracbrCsltYQBEjFAgIzkiFAc-wW7q_MkvC-bsa2v9PKI9trqUlfwfvhTS-F0aqMQiZyvOMI8RkRVapojCscMh6hda97n4bk1_oC31hz6mAeuvHWaI23w7UnXHWsi9ynVh-__INwtwwOvIdNqIG1cEWZtBtvZrUsRTKgqFkypN7217AtRGOaIeTkeOK01Cc-F50eZbmg9c",
     "has_more":false
   }

具有最大期望的实例:

max([obj.expectation for obj in mylist])