以下是一个示例代码,演示如何按百分比分割总数并获得相同的结果:
import random
def split_numbers(total, percentages):
# 将百分比转换为小数
percentages = [p / 100 for p in percentages]
# 计算每个百分比对应的数量
split_counts = [int(total * p) for p in percentages]
# 将总数减去已分配的数量,得到剩余数目
remaining = total - sum(split_counts)
# 如果存在剩余数目,则随机分配给某个百分比
if remaining > 0:
# 随机选择一个索引
index = random.randint(0, len(split_counts) - 1)
# 将剩余数目加到该百分比
split_counts[index] += remaining
return split_counts
# 示例用法
total_count = 100
percentages = [30, 40, 30]
result = split_numbers(total_count, percentages)
print(result)
该代码首先将百分比转换为小数,并计算每个百分比对应的数量。然后,它计算剩余数目,并随机将剩余数目分配给某个百分比。最后,返回每个百分比对应的数量列表。
注意:由于分配剩余数目是随机的,所以每次运行结果可能会有所不同。但是,平均下来,每个百分比对应的数量将接近于预期的百分比。
上一篇:按百分比分割数组