Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...