微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在列表理解中使用“else”

如何解决在列表理解中使用“else”

我正在使用 Python,我正在预测时装模特图像中出现的服装属性。使用以下代码构建预测:

ATTRIBUTE RECOGNITION MODEL

#Importing necessary libraries
import torch
import torchvision.models as models
from torchvision import transfor
from torch.autograd import Variable
from PIL import Image
import torch.nn as nn
import numpy as np

#Defining the functions to load and use the model
def get_tensor(img):
    tfms = transforms.Compose([
    transforms.Resize((256,256)),transforms.ToTensor()
    ])
    return tfms(Image.open(img)).unsqueeze(0)


def predict(img,label_lst,model):
    tnsr = get_tensor(img)
    op = model(tnsr)
    op_b = torch.round(op)
    op_b_np = torch.Tensor.cpu(op_b).detach().numpy()
    preds = np.where(op_b_np ==1)[1]
    sigs_op = torch.Tensor.cpu(torch.round((op)*100)).detach().numpy()[0]
    o_p = np.argsort(torch.Tensor.cpu(op).detach().numpy())[0][::-1]
    label = []
    for i in preds:
        label.append(label_lst[i])
    arg_s = {}
    for i in o_p:
        arg_s[label_lst[int(i)]] = sigs_op[int(i)]
    return label,list(arg_s.items())[:10]

#Load the model

labels = open(ATTRIBUTE_PATH,'r').read().splitlines()

model = torch.load(ATTRIBUTE_MODEL_PATH,map_location=torch.device('cpu'))
model = model.eval()

#Use the model to iterate over the rows of our clothing dataframe and adding a column with the predictions
predictions=[]
for x in df_images["Media"]:
    p= predict(x,labels,model)
    predictions.append(p)
    
    
out = [[i for i,v in lst if v > -200 else i == i[0]] for _,lst in predictions]
df_images["Attributes"] = out
df_images.head()

以上对我来说工作正常。我正在检索 i,v 中 i 的所有值,其中 v > -200。

但是,我想添加一个 else 条件指定,如果 i,v where v > -200 中没有 i 的值,则返回 i[0] for i in i,v。(即 v 所在的 i i,v) 中最高

我想这样做的原因是因为对于某些图像,现在正在返回属性预测,因为它们不满足 -200 的阈值。因此,因为我想从已识别的可能属性列表中返回最可能的属性

这是我迄今为止尝试过的方法,但它不起作用:

out = [[i for i,lst in predictions]

感谢您的帮助

解决方法

我想你的意思是:

out = [[i for i,v in lst if v > -200] or [lst[0][0]] for _,lst in predictions]

然而,正如你所看到的,很难理解并解释它的作用,这意味着有时以显式形式编写代码会更好:

out = []
for _,lst in prediction:
   member = [i for i,v in lst if v > -200]
   if not member:
       member = [lst[0][0]]
   out.append(member)

注意第一种形式:Python 中的运算符“or”和“and”与大多数其他二元运算符的行为不同。如果“或”具有“真”值,则“或”将评估其左侧的对象,否则评估右侧的对象(无论它是否具有 True 值)。 然后,在 Python 中,空序列有一个“假”值(它的计算结果为布尔值 False),因此,如果由 "> -200" 保护过滤的元素最终为空,则其中的“或”将选择右侧表达式的结果。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?