Python两列表元素随机替换与指定位置替换实现咨询
问题解决方案
已知条件
给定两个数据列表:
list_A = [2,3,4,5,33,42,21]
list_B = [1,11,35,48,19]
问题1:随机替换list_B中2个元素,生成200个唯一的新列表
实现思路
- 首先验证组合可行性:list_B共5个元素,选2个位置的组合数为
C(5,2)=10,每个替换位置可从list_A的7个元素中任选,总可能组合为10*7*7=490,大于200,可满足生成200个唯一列表的要求 - 通过集合存储已生成列表的元组形式(列表不可哈希,转元组可用于去重校验),直到集合长度达到200即可停止生成
示例代码
import random import itertools list_A = [2,3,4,5,33,42,21] list_B = [1,11,35,48,19] unique_lists = set() result = [] # 预先生成所有可选的位置组合 pos_combinations = list(itertools.combinations(range(len(list_B)), 2)) while len(result) < 200: # 随机选2个不同的位置 pos1, pos2 = random.choice(pos_combinations) # 随机选list_A的两个元素 val1, val2 = random.choice(list_A), random.choice(list_A) # 生成新列表 new_list = list_B.copy() new_list[pos1] = val1 new_list[pos2] = val2 # 转元组校验唯一性 list_tuple = tuple(new_list) if list_tuple not in unique_lists: unique_lists.add(list_tuple) result.append(new_list) # 生成的200个唯一列表存储在result变量中 print("示例生成列表:", result[0])
效果示例
输出的列表符合要求:List_1 = [*2*,11,35,48,*42*]
问题2:替换list_B前2个元素为list_A的随机元素
实现思路
固定替换索引为0、1的两个位置,直接从list_A中随机选取两个元素赋值即可,允许重复元素直接两次随机选取,要求不重复可使用random.sample方法
示例代码
import random list_A = [2,3,4,5,33,42,21] list_B = [1,11,35,48,19] new_list = list_B.copy() # 允许替换元素重复的写法 new_list[0], new_list[1] = random.choice(list_A), random.choice(list_A) # 若要求两个替换元素不重复,替换为下面的写法 # new_list[0], new_list[1] = random.sample(list_A, 2) print("生成列表:", new_list)
效果示例
输出的列表符合要求:list_2 = [*5*,*33*,35,48,19]
内容的提问来源于stack exchange,提问作者mohammad hassan moayyedian
相关产品推荐
相关产品推荐

