gpt4 book ai didi

python - 如何用字符串和numpy数组形成字典?

转载 作者:行者123 更新时间:2023-11-30 21:56:36 24 4
gpt4 key购买 nike

如何交换我的 dict 的键值对,其中键是字符串,值是 numpy 数组

word2index = {'think': array([[9.56090081e-05]]), 
'apple':array([[0.00024469]])}

现在我需要这样的输出

index2word = {array([[9.56090081e-05]]):'think', 
array([[0.00024469]]):'apple'}

最佳答案

Why Lists Can't Be Dictionary Keys

To be used as a dictionary key, an object must support the hash function (e.g. through hash), equality comparison (e.g. through eq or cmp)

That said, the simple answer to why lists cannot be used as dictionary keys is that lists do not provide a valid hash method.

但是,使用列表的字符串表示:

word2index = {'think': [9.56090081e-05], 'apple': [0.00024469]}
print({repr(v):k for k,v in word2index.items()})

输出:

{'[9.56090081e-05]': 'think', '[0.00024469]': 'apple'}

:

将列表转换为元组:

print({tuple(v):k for k,v in word2index.items()})

输出:

{(9.56090081e-05,): 'think', (0.00024469,): 'apple'}

关于python - 如何用字符串和numpy数组形成字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55471300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com