You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python按指定模式重排列表、输出结果并验证循环回归性

Python实现列表固定模式重排测试方案

核心逻辑说明

有限长度列表的固定重排本质是置换群操作,所有合法置换都存在有限循环周期,必然会在有限次操作后回到初始状态,无需担心无限循环问题。

实现步骤

  • 先做重排模式合法性校验:确保模式长度和列表长度一致,包含1到列表长度的所有整数无重复(适配示例中的1-based计数规则)
  • 循环应用重排模式,每次生成新列表后和初始列表比对,相等即终止循环
  • 所有中间排列结果统一写入指定文本文件

代码实现

def test_permutation_pattern(initial_list, pattern, output_file):
    n = len(initial_list)
    # 校验重排模式合法性
    if len(pattern) != n:
        raise ValueError("重排模式长度必须与列表长度一致")
    if set(pattern) != set(range(1, n+1)):
        raise ValueError("重排模式需包含1到列表长度的所有整数,无重复值")
    # 将1-based的模式转换为Python适配的0-based索引
    pattern_index = [x - 1 for x in pattern]
    current_list = initial_list.copy()
    # 存储所有排列结果,初始状态作为第0次结果
    permutation_records = [current_list.copy()]
    while True:
        # 应用重排规则生成新列表
        current_list = [current_list[i] for i in pattern_index]
        # 回到初始状态则终止循环
        if current_list == initial_list:
            break
        permutation_records.append(current_list.copy())
    # 写入结果到文本文件
    with open(output_file, 'w', encoding='utf-8') as f:
        for step, perm in enumerate(permutation_records):
            f.write(f"第{step}次排列结果:{perm}\n")
        f.write(f"第{len(permutation_records)}次排列结果:{initial_list}(已回到初始状态)\n")
    # 返回循环周期长度
    return len(permutation_records)

# 使用示例
if __name__ == "__main__":
    # 替换为你自己的100项初始列表
    initial_100_list = list(range(1, 101))
    # 填入你需要测试的所有重排模式
    test_pattern_list = [
        # 示例模式:前3项按给出的[3,1,2]规则重排,后续项位置不变
        [3, 1, 2] + list(range(4, 101)),
        # 可继续添加其他测试模式
    ]
    # 批量测试所有模式
    for pattern_id, pattern in enumerate(test_pattern_list):
        output_file_path = f"重排模式{pattern_id + 1}_结果.txt"
        cycle_length = test_permutation_pattern(initial_100_list, pattern, output_file_path)
        print(f"重排模式{pattern_id + 1}测试完成,循环周期为{cycle_length},结果已写入{output_file_path}")

注意事项

  • 若你使用的重排模式本身是0-based计数,删除代码中pattern_index = [x - 1 for x in pattern]这一行即可
  • 输出文本默认按UTF-8编码存储,可根据需求修改open函数的编码参数
  • 列表元素支持任意可转字符串的类型,不限于数字

内容的提问来源于stack exchange,提问作者user17026080

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:36:04