Home > front end >  Sorting max value between two lists
Sorting max value between two lists

Time:03-25

I have two lists. One with the name of cities [Milwaukee, Seattle, Minneapolis] and another list with the cities' corresponding populations [30, 45, 15].

I want to print the name of the city with the highest population (I need the code to print 'The city with the greatest population is Seattle').

CodePudding user response:

cities=["Milwaukee", "Seattle", "Minneapolis"]
population=[30, 45, 15]
print (cities[population.index(max(population))])

CodePudding user response:

You can zip the populations to the cities (in that order), then take the max between the zipped tuples. The city with the max population is the second element of the returned tuple:

cities = ["Milwaukee", "Seattle", "Minneapolis"]
population = [30, 45, 15]

print(max(zip(population, cities))[1])

Gives here Seattle

CodePudding user response:

You could create a dictionary and use the max function and print using format like this:

cities=["Milwaukee", "Seattle", "Minneapolis"]
population=[30, 45, 15]

d = dict(zip(cities,population))
{'Milwaukee': 30, 'Seattle': 45, 'Minneapolis': 15}
d
# max(d)
# 'Seattle'

print("The city with the greatest population is {}.".format(max(d)))
  • Related