Home > database >  Basic Python Question - Printing Account Name for Highest Balance (zip list)
Basic Python Question - Printing Account Name for Highest Balance (zip list)

Time:03-16

I am working on a practicing python problem. I am trying to figure out how to print a statement on what account has the highest balance. I'm sure this is much easier than I think it is, but I'm new enough to programming that I haven't been able to figure what to google to get the answer I want. If anyone has a minute to help me, I would appreciate.

account_number=["Account #1", "Account #2", "Account #3"]
total= [90, 15, 45]

So far, what I've come up with is using the zip function to put the list together.

account_totals=list(zip(account_number, total))
highest_account=max(account_totals)[1]
print(highest_account)

This gives me the number of the highest account (so prints 90), but what I really want to do is have it print Account 1 instead. And I want to make the program work so that if I can the input values and suddenly the the lists changed

account_number=["Account #1", "Account #2", "Account #3"]
total= [90, 15, 145]

That now it would print "Account 3" instead.

I hope this makes sense! I would really appreciate if someone has time to point me in the right direction.

CodePudding user response:

You can pass in a key parameter to max() that tells the function to select the element with the highest balance (in this case, the balance is located in the second element of the tuple, so we compare based on the element at index 1 for each tuple):

highest_account = max(account_totals, key=lambda x:x[1])
print(highest_account)

This prints:

('Account #1', 90)

CodePudding user response:

Use a custom key for the max function

account_totals = list(zip(account_number, total))
highest_account_name, highest_account_val = max(account_totals, key=lambda x: x[1])
print(highest_account_name)  # Account #2

Or zip with the numeric values first, the max function will sort by first element of tuple so you're done

account_totals = list(zip(total, account_number))
highest_account_val, highest_account_name = max(account_totals)
print(highest_account_name)  # Account #2

CodePudding user response:

Because the two lists are linked by index (in the order of items), you can grab the index of the highest value and return the account number. Before this works, you must separate the items in your account_number list such that they are separate elements. You currently only have one item in said list but you want to separate them as I have below so they exist as individual items.

account_number=["Account #1", "Account #2", "Account #3"]
total= [90, 15, 45]

# Get the highets value
highest_value = max(total)
# Determine the index
index = total.index(highest_value)
# Cross-reference with the accounts list
account = account_number[index]

Or with one line:

account = account_number[total.index(max(total))]
  • Related