0

I am writing a Python program that produces a list similar to the code block below. The user inputs ten numbers, which are stored in a list. It counts the number of distinct objects. The first number in each ( ) is the number the user entered, and the second value is how many times it was entered. What I need to do is essentially print out to the user "The most common number is x which was entered y times".

organizedList = [(1.0, 5), (5.0, 3)]
print max(organizedList)

I tried a normal max command, but it chooses the second value as the max even thought it was chosen less often. Thank you for your help.

jjj
  • 23
  • 1
  • 4

4 Answers4

1

As the other answers have already pointed out, you can tell the max function to only look at the second value by setting the key parameter. To output the result you can do this:

x,y = max(organizedList, key=lambda x: x[1])

print "The most common number is",x,"which was entered",y,"times."
Keiwan
  • 8,031
  • 5
  • 36
  • 49
0

Use the key option to max, which is a function that tells max what value to base the output on.

organizedList = [(1.0, 5), (5.0, 3)]
print max(organizedList, key=lambda x: x[1])

This will use the 2nd element to determine the maximum value.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
0

max has a key argument which you can use to specify on which tuple element the max should be found from.

>>> max(organizedList, key=lambda x: x[1])
(1.0, 5)

Alternatively if you aren't a fan of anonymous functions you could use operator.itemgetter to use the second element similarly with

>>> max(organizedList, key=itemgetter(1))
(1.0, 5)
miradulo
  • 28,857
  • 6
  • 80
  • 93
0

Normaly a list of tuples is sorted by the first element, but you can change the way to get the max element by the key argument

>>> from operator import itemgetter
>>> organizedList = [(1.0, 5), (5.0, 3)]
>>> max(organizedList, key=itemgetter(1))
(1.0, 5)
Querenker
  • 2,242
  • 1
  • 18
  • 29