简体   繁体   中英

How to match a lists with name and a lists with numbers

Beginner here. I want to assign each name with a number, so I can find the name of the person with the biggest number. I can find the biggest number using max(), but how do I find the name that has the biggest number?

for example:

name = ['John', 'Joe','Jae']
number = ['10','20','30']

biggest_number = max(number)
name = ????

How do I match these 2 lists to find the name?

You can use the .index() method on a list: it will give you the position of '30' in number :

position = number.index("30")
name[position]
# 'Jae'

You can get the index of that number and use the index to access the first list. Like so:

indx = number.index(biggest_number)
biggest_name = name[indx]

Or in a single line

biggest_name = name[number.index(biggest_number)]

Find the index of the biggest number then based on the index find the name.

name = ['John', 'Joe','Jae']
number = ['10','20','30']

biggest_number = max(number)
max_index = number.index(biggest_number)
print(name[max_index])

What you want is to have an "associative array" between the number and the name. In Python that is done with a dictionary, where the key is the number and the value is the name.

You could do it with this:

name = ['John', 'Joe','Jae']
number = ['10','20','30']
num_to_name = { int(number): name for number, name in zip(number, name) }
print(num_to_name[max(num_to_name)])

The notation { x: y for x, y in collection } is called a dict comprehension and is an efficient way of defining a dictionary when all values are known.

Also notice that I took the liberty to convert the numbers to integers when using them as keys, because if you keep them as strings, you might have surprises, like:

numbers = ["90", "100"]
max(numbers)
'90'

Here, as they are strings, a lexicographical order search would be performed, and as the character '9' happens after character '1', then the program would assume that '90' is bigger than '100'.

Using integers you'd get the behaviour you'd expect.

You don't want the max(number) , you want the position where the max number occurs. There exist various ways to do it, but the most straighforward is to use numpy's index = np.argmax(numbers) to get the position, and the name = names[index]

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