user9099702
user9099702

Reputation: 109

Python: sorting list via parameter in another function

I'm trying to get the fruit() function to sort using key=sortby() and then print to screen - either within fruit() or within it's own function.

It works fine when there is no fruit() function, but I'm having difficulties working out the right syntax to pass par as a parameter to be used in fruit()

fruit = [["Apples", 30], ["Bananas", 100], ["Pears", 0], ["Peaches", 20]]

def sortby(par):
    return par[1]

def fruit():
    rate = []

    fruit.sort(key=sortby, reverse=True)

    for success in fruit:
        rate.append(success[0])
        rate.append(success[1])

    str = str(rate)

print(str)

Upvotes: 2

Views: 683

Answers (1)

Stuart
Stuart

Reputation: 9858

There are several issues with your code:

  1. You need to return a value from your fruit function
  2. You need to give the fruit function a different name from the list
  3. You need to actually call the fruit function at some point
  4. Avoid using str as a variable name, as this is a built-in function in Python.

The sortby function works fine, however.

fruit = [["Apples", 30], ["Bananas", 100], ["Pears", 0], ["Peaches", 20]]

def sortby(par):
    return par[1]

def sort_fruit():
    rate = []

    fruit.sort(key=sortby, reverse=True)

    for success in fruit:
        rate.append(success[0])
        rate.append(success[1])

    return rate

print(sort_fruit())

Upvotes: 4

Related Questions