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

嵌套For循环导致主列表元素重复为最终结果的问题

问题:循环收集分形维度数据时所有子列表内容重复

我有一个包含大量EEG和PPG文件的目录,需要计算这些文件的分形维度(fractal dimension),并通过嵌套循环将所有数据收集到主列表cols中,以便后续导出为CSV文件。但运行循环后发现,cols中的所有子列表均为最后一次计算得到的结果,而非对应N-Seg组合的不同结果。

代码示例

for n in range(5,11):
    for s in range(1,3):
        fracList.clear()
        for x in dir_list:
            y = x.split('_')
            if 'PPG' in y and 'N'+str(n) in y and 'Seg'+str(s) in y:
                fracList.append(hfd.fracDim(path+"\\"+x))
        else:
            cols.append(fracList)

文件命名格式如Joe_Nature_PPG_N5_Seg1_fl10.txt,其中N的取值为5-10,Seg取值为1和2,每个N-Seg组合对应35个样本,预期cols中每个子列表含35个分形维度值,但实际所有子列表完全相同。


问题原因

核心问题是列表的引用传递特性:你始终复用同一个fracList列表对象,每次循环仅用clear()清空其内容,而非创建新列表。当你把fracList添加到cols时,实际上是把这个列表对象的引用存入了cols。因此cols中所有子列表指向的都是同一个内存地址的对象,最终所有子列表都会显示最后一次循环填充的结果。

解决方案

方案1:每次循环创建新列表(推荐)

放弃复用fracList,每次循环初始化一个新的空列表,这样每个子列表都是独立的对象:

for n in range(5,11):
    for s in range(1,3):
        fracList = []  # 每次循环新建空列表,替代clear()
        for x in dir_list:
            y = x.split('_')
            if 'PPG' in y and 'N'+str(n) in y and 'Seg'+str(s) in y:
                fracList.append(hfd.fracDim(path+"\\"+x))
        cols.append(fracList)

方案2:添加列表副本到cols

如果需要复用原列表对象,可以在添加到cols时传入列表的副本,避免引用同一对象:

for n in range(5,11):
    for s in range(1,3):
        fracList.clear()
        for x in dir_list:
            y = x.split('_')
            if 'PPG' in y and 'N'+str(n) in y and 'Seg'+str(s) in y:
                fracList.append(hfd.fracDim(path+"\\"+x))
        cols.append(fracList.copy())  # 存入副本而非原引用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:13:16