# Python3使用累计概率抽签出现死循环的问题

HiJacker 发布于 2017/08/28 14:46

``````import random
import time

def pick_pisotions(how_many):
result_positions = []
p = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0.09200879765395895, 0.10227272727272728, 0.0988514173998045, 0.010019550342130987, 0, 0, 0],
[0, 0, 0.0024437927663734115, 0.17424242424242423, 0.44477028347996095, 0.07539100684261975, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
temp_position_list = []  # tiff子图的二维坐标
temp_p_list = []  # tiff子图的被选中概率
for row in range(5):
for col in range(9):
temp_position_list.append((row, col))
temp_p_list.append(p[row][col])
print("sum =", sum(temp_p_list))

seed_index = 0
while True:  # 选取N个不重复数据
seed_index += 1
# random.seed(time.time())
random.seed(seed_index)
length_of_result = len(result_positions)
if length_of_result == how_many:  # 选够了
return result_positions
elif 0 <= length_of_result < how_many:  # 还不够
random_number = random.uniform(0, 1)
cumulative_probability = 0.0
for item_position, item_probability in zip(temp_position_list, temp_p_list):
cumulative_probability += item_probability  #
print("测试random_number = ", random_number)
print("测试cumulative_probability = ", cumulative_probability)

if random_number <= cumulative_probability:
result_positions.append(item_position)
result_positions = list(set(result_positions))  #
break
else:
print("测试random_number > cumulative_probability")
# pass
else:
print("错误：pick_tiffs()")

pick_pisotions(15)
``````