Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按值对字典python排序(word2vec)_Python_Sorting_Word2vec_Cosine Similarity - Fatal编程技术网

按值对字典python排序(word2vec)

按值对字典python排序(word2vec),python,sorting,word2vec,cosine-similarity,Python,Sorting,Word2vec,Cosine Similarity,我想按值对我的dict进行排序,但如果我应用此代码,它将不起作用(它只打印我的键值对,而不进行任何排序)。如果我将key=lambda x:x[1]更改为x[0]它将按key正确排序,因此我不明白我做错了什么 我的代码: from gensim.models.word2vec import Word2Vec from scipy.spatial.distance import cosine e_science = Word2Vec.load("clean_corpus_science

我想按值对我的
dict
进行排序,但如果我应用此代码,它将不起作用(它只打印我的
键值对,而不进行任何排序)。如果我将
key=lambda x:x[1]更改为x[0]
它将按
key
正确排序,因此我不明白我做错了什么

我的代码:

from gensim.models.word2vec import Word2Vec
from scipy.spatial.distance import cosine

e_science = Word2Vec.load("clean_corpus_science.model")
e_pokemon = Word2Vec.load("clean_corpus_pokemon.model")

science_vocab = list(e_science.wv.vocab)
pokemon_vocab = list(e_pokemon.wv.vocab)

vocab_intersection = list(set(science_vocab).intersection(set(pokemon_vocab)))

similarity = []
for i in range(0, len(vocab_intersection)):
  similarity.append(1-cosine(e_science[vocab_intersection[i]], e_pokemon[vocab_intersection[i]]))

hashmap = {}
for i in range(0, len(similarity)):
  hashmap[vocab_intersection[i]] = {similarity[i]} 

dict(sorted(hashmap.items(), key=lambda x: x[1]))

您正在尝试对集合进行排序,而Python不确定如何对它们进行排序。把你的分数从集合中拿出来,然后你就可以按预期排序了

dict(sorted(hashmap.items(), key=lambda x: tuple(x[1])[0]))

不过这很难看,您可能需要在单独的步骤中进行清理。

您使用的是哪种python版本?在旧的字典中,字典是无序的3.6.9,我使用colab notebooksorting和
lambda x:x[0]
按键排序,使用
lambda x:x[1]
按值排序我已经尝试过了,但是x[1]不起作用(而是x[0]按键正确排序),你能在你的hashmap中共享一个值吗?它起作用了!非常感谢。