j.doe
j.doe

Reputation: 77

How to use the max array

maxPrice = 0
    for item in cont["price_usd"]:
        if(item[1] > maxPrice):
           maxPrice = (item[1])

    print (maxPrice)

I'm trying to find the max price in an array, and I'm trying to use the max() method to make my code simpler. cont["price_usd"] is a list of [amount_coins, price] and I'm trying to compare all of the prices.

I tried doing this:

list = cont["price_usd"]:
max(list)

but I don't know how to express that I only want the second subitem in each item.

Upvotes: 0

Views: 43

Answers (2)

MegaIng
MegaIng

Reputation: 7886

You should use the key keyword of the max function:

maxPrice = max(cont["price_usd"], key=lambda e: e[1])[1]

Upvotes: 0

ihatecsv
ihatecsv

Reputation: 542

Use map() and max()

prices = list(map(lambda x: x[1], cont["price_usd"]))
maxPrice = max(prices)
print(maxPrice)

The map function here uses the lambda function lambda x: x[1] to take each element of cont["price_usd"], extract the element at index 1, and then put that into a list. Then we call max to find the largest value in that list.

Upvotes: 1

Related Questions