如何在列表python中编写if else条件?

时间:2016-08-11 18:06:27

标签: python django python-2.7 python-3.x django-views

我得到了图像的像素大小,我需要在像素处写一个if条件

如果jpg或tiff:做点什么 别的'0,0'

我如何写下面的代码?

def get(self, request, **response_kwargs):    

    main_request = MediaRequest.objects.get(request_unique_id=self.kwargs['request_unique_id'])

    files = MediaFile.objects.filter(request=main_request)

    files_list = []

    for media_file in files:
        files_list.append ({
                'preview' : "/render/" + str(main_request.request_unique_id) + "/" + media_file.filename,        
                'name' : media_file.filename,        
                'status' : media_file.status,
                'comment' : media_file.comment,
                'id':media_file.id,
                'pixel' : 
                           if "jpg" not in media_file.filename:
                              Image.open(settings.MEDIA_ROOT + main_request.request_unique_id + "/"+ media_file.filename).size
                           else:
                               return '0, 0'
            })

2 个答案:

答案 0 :(得分:0)

参见三元运算符(或条件表达式):"X if C else Y"

https://www.python.org/dev/peps/pep-0308/

for media_file in files:
    files_list.append ({
            'preview' : "/render/" + str(main_request.request_unique_id) + "/" + media_file.filename,        
            'name' : media_file.filename,        
            'status' : media_file.status,
            'comment' : media_file.comment,
            'id':media_file.id,
            'pixel' : Image.open(settings.MEDIA_ROOT + main_request.request_unique_id + "/"+ media_file.filename).size if "jpg" not in media_file.filename else '0, 0'
        })

答案 1 :(得分:0)

class BaseClass
{
    protected void Update()
    {
        if(someArgument)
        {
            this.InnerUpdate();
        }
    }

    protected virtual void InnerUpdate()
    {
    }
}

class Foo : BaseClass
{
    protected override void InnerUpdate()
    {
        //Some other code
    }
}