写一个函数,该函数会在指定的随机种子下,从指定的订单数据中无放回地随机抽取指定数量的订单,计算样本中给予了折扣的订单数量比例和给予折扣金额的比例,并打印出“给予折扣订单数量比例为…%,给予折扣金额比例为…%”。
时间: 2024-12-15 09:29:09 浏览: 8
首先,我们可以创建一个名为`random_sample_analysis`的Python函数,它接受四个参数:订单数据列表(orders)、随机种子(seed)、抽取的数量(sample_size),以及是否需要计算折扣金额比例(calculate_discount_amount)。下面是一个简单的实现:
```python
import random
def random_sample_analysis(orders, seed, sample_size, calculate_discount_amount=True):
# 设置随机种子
random.seed(seed)
# 从订单中无放回地随机抽取指定数量的订单
sampled_orders = random.sample(orders, sample_size)
# 初始化计数器
total_discounted_orders = 0
total_discount_amount = 0
for order in sampled_orders:
if "discount" in order and order["discount"] > 0: # 检查是否有折扣
total_discounted_orders += 1
if calculate_discount_amount:
total_discount_amount += order["discount"]
# 计算比例并打印结果
discount_rate = (total_discounted_orders / sample_size) * 100 if sample_size else 0
if calculate_discount_amount:
avg_discount_rate = (total_discount_amount / total_discounted_orders) if total_discounted_orders else 0
print(f"给予折扣订单数量比例为{discount_rate:.2f}%, 给予折扣金额比例为{avg_discount_rate:.2f}%")
else:
print(f"给予折扣订单数量比例为{discount_rate:.2f}%")
# 使用示例
orders_data = [
{"id": 1, "discount": 50}, # 订单有折扣
{"id": 2, "discount": 0}, # 订单无折扣
{"id": 3, "discount": 100}, # 订单有大额折扣
# 更多订单...
]
random_sample_analysis(orders_data, 42, 3)
```
在这个例子中,函数会从给定的订单数据中随机选择`sample_size`个订单,然后统计其中有多少订单给予了折扣,以及如果有计算需求,还会计算折扣金额的比例。
阅读全文