Python实现多列表间重复元素的随机移除方法
多列表随机移除重复元素
给定三个列表:
x = [0,1,2,3] y = [0,4,3,5] z = [1,6,7,8]
需要实现功能:随机移除这三个列表中所有的重复元素——即每个元素最终仅保留在其中一个列表里,且每次运行程序得到的元素分布结果不同。
期望输出示例1:
x = [1,2,3] y = [0,4,5] z = [6,7,8]
期望输出示例2:
x = [0,1,2,3] y = [4,5] z = [6,7,8]
现有相关方案大多针对单列表去重,无法满足需求。
我的尝试(未完成)
duplicatelist = [] for number in y: if number in x: duplicatelist.append(number) for number in z: if number in x or number in y: duplicatelist.append(number) # 不知道接下来该怎么做
解决方案思路
- 先收集所有元素,统计每个元素出现的列表位置
- 对每个重复元素,随机选择一个列表保留它,从其他列表中移除该元素
- 非重复元素保持原位置不变
实现代码
import random def random_remove_duplicates(x, y, z): # 复制原列表,避免修改原始数据 lists = {'x': x.copy(), 'y': y.copy(), 'z': z.copy()} # 记录每个元素所在的所有列表 element_locations = {} for name, lst in lists.items(): for elem in lst: if elem not in element_locations: element_locations[elem] = [] element_locations[elem].append(name) # 处理重复元素 for elem, locations in element_locations.items(): if len(locations) > 1: # 随机选一个列表保留当前元素 keep_list = random.choice(locations) # 从其他列表中移除该元素 for lst_name in locations: if lst_name != keep_list: lists[lst_name] = [e for e in lists[lst_name] if e != elem] return lists['x'], lists['y'], lists['z'] # 测试运行 x = [0,1,2,3] y = [0,4,3,5] z = [1,6,7,8] new_x, new_y, new_z = random_remove_duplicates(x, y, z) print(f"x = {new_x}") print(f"y = {new_y}") print(f"z = {new_z}")
代码说明
- 复制原列表操作避免了对原始数据的直接修改
- 通过
element_locations字典记录每个元素的分布位置,方便后续处理重复项 - 利用
random.choice随机选择保留元素的列表,确保每次运行结果不同
内容的提问来源于stack exchange,提问作者Difio
相关产品推荐
相关产品推荐

