Python中如何在排除指定内容后对列表执行shuffle打乱操作
功能实现方案
实现逻辑
- 第一步:遍历原列表,分别记录需保留元素的位置和需打乱的元素集合
- 第二步:调用
random.shuffle()打乱待打乱的元素集合 - 第三步:初始化和原列表等长的结果列表,先将保留元素填入原对应位置,再将打乱后的元素依次填入剩余空位
完整代码
import random def shuffle_with_fixed_content(original_list, fixed_content): # 收集保留元素的位置、以及需要打乱的元素 fixed_positions = [] shuffle_candidates = [] for idx, item in enumerate(original_list): if item == fixed_content: fixed_positions.append(idx) else: shuffle_candidates.append(item) # 打乱候选元素 random.shuffle(shuffle_candidates) # 构建结果列表 result = [None] * len(original_list) # 先填固定元素 for pos in fixed_positions: result[pos] = fixed_content # 填打乱后的元素 shuffle_ptr = 0 for i in range(len(result)): if result[i] is None: result[i] = shuffle_candidates[shuffle_ptr] shuffle_ptr += 1 return result # 测试示例 if __name__ == "__main__": input_list = ['Hello', 'Middle school student', 'I am'] keep_content = 'I am' print(shuffle_with_fixed_content(input_list, keep_content))
运行后输出样例和你预期一致,每次运行非保留内容的位置都会随机变化,指定保留的I am始终在原有位置。
扩展说明
如果需要同时保留多个不同内容,只需修改判断逻辑即可,比如把入参fixed_content改成列表,判断条件换成if item in fixed_content_list,就能支持多元素位置固定。
内容的提问来源于stack exchange,提问作者유현석
相关产品推荐
相关产品推荐

