如何根据索引dict中的索引对列表进行排序



例如:

words = ['this', 'test', 'a', 'is']
word_index_map = {'this':(1,5), 'is':(5,7),'a':(7,8), 'test': (11,15)}

word_index_map存储文本中每个单词的开始和结束位置。我想根据每个单词的结束位置对单词进行排序,这样单词就会被排序为:

words = ['this', 'is', 'a', 'test']

他们的最终位置将是:

end_pos = [5, 7, 8, 15]

如何进行此排序?我正在努力做到这一点:

def take_position(word, word_index_map):
return word_index_map[word][1]
words.sort(key=take_position)

但这无法将word_dict传递到take_position函数中,因此会出现错误:TypeError: take_position() missing 1 required positional argument: 'word_index_map'

有没有办法将word_index_map传递给函数,或者用其他方法对其进行排序?

您可以像一样放置lambda

words.sort(key=lambda word: take_position(word,  word_index_map))

或者不使用您的函数,而是将逻辑直接放入lambda

words.sort(key=lambda word: word_index_map[word][1]

最新更新