[英]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,你的方法的问题是,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.