以下是一个按值加权选择一行索引的示例代码:
import random
def weighted_choice(weights):
total = sum(weights)
threshold = random.uniform(0, total)
cumulative_weight = 0
for i, weight in enumerate(weights):
cumulative_weight += weight
if cumulative_weight > threshold:
return i
def weighted_index_choice(matrix, weights):
row_weights = [sum(row) for row in matrix]
chosen_row_index = weighted_choice(row_weights)
return chosen_row_index
# 示例使用
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
weights = [0.1, 0.3, 0.6]
chosen_index = weighted_index_choice(matrix, weights)
chosen_row = matrix[chosen_index]
print("Chosen row index:", chosen_index)
print("Chosen row:", chosen_row)
在这个示例中,weighted_choice
函数用于按权重随机选择一个索引。它首先对权重进行归一化,然后生成一个随机的阈值。然后,它遍历权重列表,并在累加权重大于阈值时返回对应的索引。
weighted_index_choice
函数使用weighted_choice
函数来选择一个行索引。它首先计算每一行的权重之和,并将这些权重传递给weighted_choice
函数。然后,它返回被选中的行索引,并通过该索引从矩阵中获取相应的行。
最后,我们使用示例矩阵和权重调用weighted_index_choice
函数,并打印出被选中的行索引和对应的行。
上一篇:按值将字典保存为CSV
下一篇:按值解构向量