简体   繁体   English

如何将布尔函数应用于列表中的每个元素?

[英]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))

I want to to apply bool_gen to each element in purchases_prices and not to the whole list .我想将 bool_gen 应用于 purchase_prices 中的每个元素不是整个列表 What happens:发生什么了:

have_discount = [10, 15, 20] and no_discount = []

What i'm looking for:我在找什么:

have_discount = [10,20]  and no_discount = [30]

Call bool_gen() inside the loop.在循环内调用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 function 应用于列表的每个元素 - Apply function to each element of a list 如何将 function 应用于列表中的每个元素,然后制作输出列表? - How to apply a function to each element in a list, then make a list of the outputs? 如何在没有 for 循环或 lambda 函数的情况下将 function 应用于列表的每个元素? - How to apply a function to each element of a list without for loops or lambda functions? 将 function 应用于列表的每个元素并重命名 - Apply function to each element of list and rename 将函数应用于列表递归的每个元素 - Apply function to each element of list recursion 我可以运行多个 DataFrame 并将 function 应用于每个列表吗? - can I run multiple DataFrames and apply a function to each list? 如何在Python中为矩阵中的每个元素应用函数? - How to apply a function for each element in a matrix in Python? 如何将 function 应用于 pandas dataframe 中的每一行? - How can I apply a function to each row in a pandas dataframe? 如何在Python中为每个分组应用用户定义的函数 - How can I apply a user defined function for each grouping in Python Python:对于每个列表元素,在列表中应用一个函数 - Python: For each list element apply a function across the list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM