首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据python 3中函数返回的数组检索字典键值对

如何根据python 3中函数返回的数组检索字典键值对
EN

Stack Overflow用户
提问于 2020-05-15 15:10:03
回答 3查看 287关注 0票数 0

我刚开始编写python代码,其中一个函数将返回一个numpy.ndarray,其中6个值如下所示

[1 0 1 0 1 1]

这些实际上是对多类分类模型的预测,如果匹配These 0,则值为1。

我想给这六个预测一些意义,为此我创建了一本字典如下:

代码语言:javascript
复制
toxics = {1:'Toxic', 2:'Severely Toxic', 3:'Obscene', 4:'Threat', 5:'Insult', 6:'Identity Hate'}

我如何映射/链接我的个人预测与字典,并显示/打印一些消息给用户。例如,在上面的数据中,类似于:

代码语言:javascript
复制
"The text is Toxic, Obscene, Insult, Identity Hate" as I have a prediction of '1' at 0,2,4,5 position in the array.

提前谢谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-05-15 15:20:42

以下是实现上述结果的简单理解:

代码语言:javascript
复制
arr = [1, 0, 1, 0, 1, 1]
toxic_str = ",".join([toxics[i] for i, val in enumerate(arr, 1) if val == 1])
print("This text is", toxic_str)

枚举(arr,1)将返回具有索引(从1开始)和值的元组列表。

希望这能帮上忙!

票数 2
EN

Stack Overflow用户

发布于 2020-05-15 15:25:54

这里是一个示例代码,您如何做到这一点:

代码语言:javascript
复制
import numpy as np
results =np.array([1,0,1,0, 1, 1])
toxics = {1:'Toxic', 2:'Severely Toxic', 3:'Obscene', 4:'Threat', 5:'Insult', 6:'Identity Hate'}
strings =[toxics[k] for k in (np.argwhere(results==1)+1).reshape(-1) if k in toxics]
'The text is ' + ', '.join(strings)+' as I have a prediction of 1 at ' + ', '.join(np.char.mod('%d',(np.argwhere(results==1)).reshape(-1)))

输出:

代码语言:javascript
复制
'The text is Toxic, Obscene, Insult, Identity Hate as I have a prediction of 1 at 0, 2, 4, 5'
票数 1
EN

Stack Overflow用户

发布于 2020-05-15 15:30:26

你不需要一个白痴,你可以简单地用拉链把你的预测和你的毒物联系起来。然后,您只需使用一个列表理解得到的是1,您可以使用np.where来获取索引值。

代码语言:javascript
复制
from numpy import array, where

preds = array([1, 0, 1, 0, 1, 1])
toxics = ["Toxic", "Severely Toxic", "Obscene", "Threat", "Inuslt", "Identity Hate"]
results = [toxic for pred, toxic in zip(preds, toxics) if pred == 1]
indexs = where(preds == 1)

print("'The text is", ", ".join(results) + "' as i have a prediction of '1' at",  ",".join([str(i) for i in indexs[0]]))

输出

代码语言:javascript
复制
'The text is Toxic, Obscene, Inuslt, Identity Hate' as i have a prediction of '1' at 0,2,4,5
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61822447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档