You can define generator function which will yield elements until cumulative sum reach some limit:
def iter_until(src, limit, key):
cumulative_sum = 0
for element in src:
yield element
cumulative_sum += key(element)
if cumulative_sum >= limit:
break
Let's generate input similar to your:
from collections import namedtuple
from random import shuffle
product = namedtuple("product", "name quantity")
total_quantity = 15000
products = [product(f"product{i}", total_quantity // (2 ** i)) for i in range(1, 101)]
shuffle(products)
Now you can iterate over generator function. You can create list of top 80% of sales:
sorted_products = sorted(products, key=lambda x: x.quantity, reverse=True)
top_80_percent = list(iter_until(sorted_products, total_quantity * 0.8, lambda x: x.quantity))
You can create dict (what you're trying to do in code form question):
sorted_products = sorted(products, key=lambda x: x.quantity, reverse=True)
top_80_percent = {p.name: p.quantity for p in iter_until(sorted_products, total_quantity * 0.8, lambda x: x.quantity)}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…