简体   繁体   English

Python 使用用户 function 进行列表排序。 (错误)

[英]Python list sorting with user function. (Error)

i have a list of strings which are split by a space.我有一个由空格分隔的字符串列表。 i want to sort the list by the second split value of the strings.我想按字符串的第二个拆分值对列表进行排序。

it works, if i use lambda:它有效,如果我使用 lambda:

Names = ['Ccc Eee', 'Bbb Aaa', 'Aaa Bbb', 'Zzz Zzz', 'Ddd Ddd']
# Names.sort(key=lambda name: name.split(' ')[1])
# print(Names) # ['Bbb Aaa', 'Aaa Bbb', 'Ddd Ddd', 'Ccc Eee', 'Zzz Zzz']

but if i want to sort it without using lambda, it shows error:但是如果我想在不使用 lambda 的情况下对其进行排序,则会显示错误:

def mysort(name):
    for i in range(0, len(name)):
        return name[i].split(' ')[1]

Names.sort(key=mysort(Names))
print(mysort(Names))

# output:
# Names.sort(key=mysort(Names))
# TypeError: 'str' object is not callable

what am i doing wrong?我究竟做错了什么?

Update:更新:

def mysort(name):
    return name.split(' ')[-1]

Names.sort(key=mysort)
print(Names) # ['Bbb Aaa', 'Aaa Bbb', 'Ddd Ddd', 'Ccc Eee', 'Zzz Zzz']

Two problems.两个问题。

  • You should not call the function.您不应调用 function。

    Just like you are doing就像你正在做的那样

    Names.sort(key=lambda name: name.split(' ')[1])

    and not并不是

    Names.sort(key=lambda name: name.split(' ')[1](Names))

    , you should do , 你应该做

    Names.sort(key=mysort)

    and not并不是

    Names.sort(key=mysort(Names))
  • You don't need the loop in the function:您不需要 function 中的循环:

     def mysort(name): return name.split(' ')[1]
def mysort(name):
    return name.split(' ')[1]

Names = ['Ccc Eee', 'Bbb Aaa', 'Aaa Bbb', 'Zzz Zzz', 'Ddd Ddd']
Names.sort(key=mysort)
print(Names)

This will give you the exact answer.这会给你准确的答案。
And the problem with your approach is,你的方法的问题是,

  1. inside your mysort function you are using loop which you shouldn't在你的 mysort function 里面你正在使用你不应该使用的循环
  2. you are passing argument to the function while mentioning key which you shouldn't because the value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.您正在向 function 传递参数,同时提到您不应该提到的键,因为键参数的值应该是一个 function ,它接受一个参数并返回一个用于排序目的的键。

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

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