简体   繁体   中英

Inner loop on condition in list comprehension

I have a function to check availability of product and its variations. both model has quantity_left field.

If a product has variations i want to get quantity_left from variation, otherwise i will take quantity_left from product.

def check_quota(products):
    q_list = []
    for p in products:
        if p.has_variations:
            for v in p.variations:
                q_list.append(v.quantity_left)
        else:
            q_list.append(p.quantity_left)
    return sum(q_list) 

So above function will return either 0 or any number . if it is zero means product sold out.

Above code is working fine, but i want to optimize this function using list comprehension.

I tried this but this doesn't seems to work.

return sum([v.quantity_left if p.has_variations else p.quantity_left for p in products for v in i.variations])

How can i apply if p.has_variations on inner loop.

UPDATE

suppose i have 3 products under shirt category

[
  {
    "name":"full sleve", 
    "has_variations": True, 
    "variations":[
       {
         "type": "S size", 
         "quantity_left": 3
       }, 
       {
         "type": "L size", 
         "quantity_left": 0
       }
     ]
  },
  {
    "name":"half sleve", 
    "has_variations": False, 
    "quantity_left": 0
  },
  {
    "name":"sleve less", 
    "has_variations": False, 
    "quantity_left": 10
  }
]

# it will return 13 means not sold out.

The code below should do the trick.

def check_quota(products):
    return sum(sum(v.quantity_left for v in p.variations) if p.has_variations else p.quantity_left for p in products)

Without the actual data, or any example of input-desired output, it is hard to come up with a working solution. The above code is a blind translation.


From your EDIT, it seems that you are working with dictionaries and not classes. If that is indeed the case, use the following instead:

def check_quota(products):
    return sum(sum(v['quantity_left'] for v in p['variations']) if p['has_variations'] else p['quantity_left'] for p in products)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM