python - 如何将布尔函数应用于列表中的每个元素?
问题描述
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 应用于 purchase_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))
推荐阅读
- reactjs - formik + yup 和验证子反应组件中的字段
- r - ggplot, sf package, 如何在地图上制作简单的饼图
- python - 如何使用 ALAudioDevice“订阅”方法调用“处理”函数
- c# - 如何从列表中删除项目
在使用多个线程枚举列表时? - python - 写入新文件时找不到文件
- react-native - Xcode 构建错误:PhaseScriptExecution Strip\ Frameworks /appName.build/Debug-iphonesimulator/PROD.build/Script-8CBD27422B744FC9C0407AA3.sh
- python - 访问我有权访问的 Amazon S3 上某些子文件夹(前缀)下的对象
- sql - 查询以获取 Schema/DB 中具有特定列 VALUE 的所有表
- javascript - 如何在 JavaScript 中编辑组合框的默认值
- css - 许多 CSS 变量对性能的影响