如何从指定列表的列表采样生成满足全值覆盖的16元素列表?
问题描述
我有一个嵌套列表probe_list,需要从中随机选取值生成probe列表,但当前用random.choice()循环的方式可能遗漏某些值(比如示例里的'3'),导致后续代码报错。生成的probe列表必须满足:
- 恰好16个元素;
- 每个索引位置只能选对应子列表的两个值之一(比如probe[0]只能是'7'或'6');
- 列表必须包含'1'到'8'每个值至少一次。
当前代码及问题示例:
probe_list = [['7', '6'], ['5', '8'], ['3', '2'], ['1', '4'], ['7', '6'], ['1', '4'], ['5', '8'], ['7', '6'], ['1', '4'], ['3', '2'], ['7', '6'], ['1', '4'], ['7', '6'], ['1', '4'], ['5', '8'], ['3', '2']]
probe=[] for i in range(len(probe_list)): choose = random.choice(probe_list[i]) probe.append(choose)
生成的不合格probe(缺少'3'):
probe = ['7', '8', '2', '1', '6', '1', '5', '6', '4', '2', '7', '4', '6', '4', '8', '2']
解决方案一:循环生成直到满足条件
这种方法简单直接,针对16元素的小列表,重复生成的开销可以忽略。核心逻辑是生成随机probe后,检查是否包含所有必需值,不满足就重新生成。
import random probe_list = [['7', '6'], ['5', '8'], ['3', '2'], ['1', '4'], ['7', '6'], ['1', '4'], ['5', '8'], ['7', '6'], ['1', '4'], ['3', '2'], ['7', '6'], ['1', '4'], ['7', '6'], ['1', '4'], ['5', '8'], ['3', '2']] required_values = {'1', '2', '3', '4', '5', '6', '7', '8'} while True: probe = [random.choice(sublist) for sublist in probe_list] # 检查是否覆盖所有必需值 if set(probe) >= required_values: break print(probe)
解决方案二:先确保必需值被选中,再填充剩余位置
这种方法避免重复生成,先为每个必需值分配可选取它的位置,强制选中后再随机填充剩余位置,一次生成即可满足要求。
import random probe_list = [['7', '6'], ['5', '8'], ['3', '2'], ['1', '4'], ['7', '6'], ['1', '4'], ['5', '8'], ['7', '6'], ['1', '4'], ['3', '2'], ['7', '6'], ['1', '4'], ['7', '6'], ['1', '4'], ['5', '8'], ['3', '2']] required_values = {'1', '2', '3', '4', '5', '6', '7', '8'} # 建立「值」到「可选索引位置」的映射 value_to_indices = {} for idx, sublist in enumerate(probe_list): for val in sublist: if val not in value_to_indices: value_to_indices[val] = [] value_to_indices[val].append(idx) # 为每个必需值分配唯一的位置,确保不重复 assigned_indices = set() probe = [None] * len(probe_list) for val in required_values: # 筛选未被占用的可选位置 available_indices = [idx for idx in value_to_indices[val] if idx not in assigned_indices] selected_idx = random.choice(available_indices) probe[selected_idx] = val assigned_indices.add(selected_idx) # 填充剩余未分配的位置 for idx in range(len(probe)): if probe[idx] is None: probe[idx] = random.choice(probe_list[idx]) print(probe)
方法对比
- 方案一:代码简洁,适合小列表场景,无需复杂逻辑;
- 方案二:无重复生成开销,适合列表较长、必需值较多的场景,稳定性更高。
内容的提问来源于stack exchange,提问作者cjb10
相关产品推荐
相关产品推荐

