简体   繁体   English

Python:通过另一个函数中的参数对列表进行排序

[英]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. 我试图让fruit()函数使用key=sortby()进行排序,然后打印到屏幕上-在fruit()还是在它自己的函数中。

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()函数时,它可以正常工作,但是我很难确定正确的语法以将par作为参数用于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)

There are several issues with your code: 您的代码有几个问题:

  1. You need to return a value from your fruit function 您需要从fruit函数返回一个值
  2. You need to give the fruit function a different name from the list 您需要为fruit功能指定一个与列表不同的名称
  3. You need to actually call the fruit function at some point 您实际上需要在某个时候调用fruit函数
  4. Avoid using str as a variable name, as this is a built-in function in Python. 避免将str用作变量名,因为这是Python中的内置函数

The sortby function works fine, however. 但是, sortby函数工作正常。

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM