如何在Python循环中避免随机生成的points_in_code索引重复?
解决随机索引不重复的方案
方法1:预生成打乱的索引列表(改动最小)
先把points_in_code的所有索引生成一个列表,打乱顺序后在循环里依次取用,就能避免重复,而且几乎不改动原有核心代码:
import random # 新增:生成所有索引并打乱顺序 shuffled_indices = list(range(len(points_in_code))) random.shuffle(shuffled_indices) stuff_so_far = [intl_pt] for i in range(0, num_pts - 1): # 改动此处:从打乱的列表按顺序取索引,替代randint rdm = shuffled_indices[i] a = (stuff_so_far[i][0] + points_in_code[rdm][0]) // 2 b = (stuff_so_far[i][1] + points_in_code[rdm][1]) // 2 stuff_so_far.append((a, b))
注意:要保证num_pts - 1的数值不超过len(points_in_code),否则会出现索引越界报错。
方法2:用random.sample直接取不重复索引
如果不想打乱整个索引列表,可以直接用random.sample一次性取出需要数量的不重复随机索引:
import random # 直接取出num_pts-1个不重复的随机索引 selected_indices = random.sample(range(len(points_in_code)), num_pts - 1) stuff_so_far = [intl_pt] for i in range(0, num_pts - 1): rdm = selected_indices[i] a = (stuff_so_far[i][0] + points_in_code[rdm][0]) // 2 b = (stuff_so_far[i][1] + points_in_code[rdm][1]) // 2 stuff_so_far.append((a, b))
random.sample会自动确保取出的索引不重复,同样需要保证num_pts - 1 <= len(points_in_code),否则会触发参数错误。
内容的提问来源于stack exchange,提问作者new_programmer_python
相关产品推荐
相关产品推荐

