如何将布尔函数应用于列表中的每个元素?
How can I apply a boolean function to each element in a list?
def bool_gen(p):
p = float(p)
if p > 100 or p < 0:
p = 0.5
elif 1 <= p <= 100:
p = p / 100
return random.random() < p
def apply_discount(v, b):
if b == True:
v = v * 0.5
return v
elif b == False:
return v
p = int(random.randint(0,200))
b = bool_gen(p)
purchases_prices = [20,30,40,50]
have_discount = []
no_discount = []
for each_price in purchases_prices:
if b == True
have_discount.append(apply_discount(each_price,b))
elif b == False:
no_discount.append(apply_discount(each_price,b))
我想将bool_gen应用于purchases_prices和中的每个元素不是整个列表。
会发生什么:
have_discount = [10, 15, 20] and no_discount = []
我在找什么:
have_discount = [10,20] and no_discount = [30]
在循环内调用bool_gen()
。
for each_price in purchases_prices:
b = bool_gen(p)
if b:
have_discount.append(apply_discount(each_price,b))
else:
no_discount.append(apply_discount(each_price,b))
def bool_gen(p):
p = float(p)
if p > 100 or p < 0:
p = 0.5
elif 1 <= p <= 100:
p = p / 100
return random.random() < p
def apply_discount(v, b):
if b == True:
v = v * 0.5
return v
elif b == False:
return v
p = int(random.randint(0,200))
b = bool_gen(p)
purchases_prices = [20,30,40,50]
have_discount = []
no_discount = []
for each_price in purchases_prices:
if b == True
have_discount.append(apply_discount(each_price,b))
elif b == False:
no_discount.append(apply_discount(each_price,b))
我想将bool_gen应用于purchases_prices和中的每个元素不是整个列表。 会发生什么:
have_discount = [10, 15, 20] and no_discount = []
我在找什么:
have_discount = [10,20] and no_discount = [30]
在循环内调用bool_gen()
。
for each_price in purchases_prices:
b = bool_gen(p)
if b:
have_discount.append(apply_discount(each_price,b))
else:
no_discount.append(apply_discount(each_price,b))