Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

entry function for python sort function

I'm trying to make an small terminal search engine (python 3.9, VS Code) and I wrote this function as the key function for sort. When I don't write the list parameter, list.index is meaningless and when I write it, it returns an error, could you check it out?

def soort(self, keyword):
    return self.index(keyword)
list_high = []
listname = ['breaking bad', 'dark', 'stranger things',
             'vikings', 'game of thrones', 'prison break',
             'sherlock', 'silicon valley', 'lost', 'friends']
search = 'br'
for name in listname:
    if search in name:
        list_high.append(name)
list_high.sort(key=soort(list_high, search))
print(list_high)
question from:https://stackoverflow.com/questions/65862417/entry-function-for-python-sort-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
list_high.sort(key=soort(list_high, search))

This calls soort(list_high, search) once then passes its return value (an integer) as the key argument for sort, which makes no sense (integers are not callable).

You need to make sure to pass in a callable.

You should also consider using .find instead of .index, as .index will raise a ValueError if it can't find the searched string. .find will return -1.

list_high.sort(key=lambda word: word.find('br'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...