Home > OS >  Compare attributes of objects in lists in python
Compare attributes of objects in lists in python

Time:06-16

I'm working on a program that plays "Guess Who?". I want a computer player to decide on the best question to ask.

I already have code which can determine the expected value for how many candidates will be eliminated for a certain guess, which I compute in separate variables and put into a list:

# blackHairExpect = expected number of candidates remaining
# by asking about black hair; etc.
compareExpect = [blackHairExpect, blondeHairExpect, ...]

Then I try to get the lowest value:

minExpect = min(compareExpect)

However, this only tells me how good the best guess is; it doesn't tell me which guess to use. How can I find that out? For example, if blackHairExpect was the lowest value, how can I know that this value results from asking about black hair?

I tried isolating the lowest value(s):

lowestExpect = [x for x in compareExpect if x == min(compareExpect)]

but this also does not solve the problem.

CodePudding user response:

Use a list of tuples of the attribute name and value. Then you can minimize the value and return the whole tuple.

compareExpect = [('blackHair', blackHairExpect), ('blondeHair', blondHairExpect), ...]
minAttr, minValue = min(compareExpect, key=lambda e: e[1])
  • Related