python - Python 3 中列表内容发生意外更改

标签 python python-3.x

我正在构建一个示例来创建一个列表的所有子集: 我的代码如下,我将结果值复制到另一个临时列表并在临时列表中进行操作,但不知道为什么在步骤 1 和步骤 3 中我打印的“结果”不同。我还没有做任何改变。

a=[1,2,3]

result=[]
temp=[]


def sub_sets(i,result):
    print("1start result:",result)
    temp=result[:]
    for j in range(len(temp)):
        temp[j].append(i)
    temp.append([i])
    print("2temp:",temp)
    print("3 middle result:",result)
    result.extend(temp)
    print("4end result:",result)


for i in range(len(a)):
    sub_sets(a[i],result)

Results:
1start result: []
2temp: [[1]]
3 middle result: []
4end result: [[1]]
1start result: [[1]]
2temp: [[1, 2], [2]]
3 middle result: [[1, 2]]
4end result: [[1, 2], [1, 2], [2]]
1start result: [[1, 2], [1, 2], [2]]
2temp: [[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [3]]
3 middle result: [[1, 2, 3, 3], [1, 2, 3, 3], [2, 3]]
4end result: [[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [1, 2, 3, 3], [1, 2, 3, 3],  [2, 3], [3]]         

最佳答案

Result 和 temp(函数的参数)是全局变量,因此需要特殊处理。下面的代码没有这个问题:

a=[1,2,3]
def sub_sets(i,result):
    print("1start result:",result)
    temp=result[:]
    for j in range(len(temp)):
        temp[j].append(i)
    temp.append([i])
    print("2temp:",temp)
    print("3 middle result:",result)
    result.extend(temp)
    print("4end result:",result)

for i in range(len(a)):
    result1=[]
    sub_sets(a[i],result1)

输出:

1start result: []
2temp: [[1]]
3 middle result: []
4end result: [[1]]
1start result: []
2temp: [[2]]
3 middle result: []
4end result: [[2]]
1start result: []
2temp: [[3]]
3 middle result: []
4end result: [[3]]

关于python - Python 3 中列表内容发生意外更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48199899/

相关文章:

python - 基于列合并重复项?

python - 如何在 gensim 中使用 mallet 设置主题模型的随机种子?

python 异步: Wait in coroutine for intermediate result of another coroutine

python-3.x - Seaborn 设置 figsize=(x,y) 关于 tight_layout "tight_layout cannot make axes height small enough to accommodate all axes decorations"的错误和警告

python-3.x - 从 Flask 导入 Flask 失败,出现语法错误 : invalid syntax

python - 将张量从形状 (n, h, w, c) reshape 为 (n, h * w, c)

python - NetworkX:检查两个图是否具有相同的形状和相同的节点属性

python - Flask 和 PyJWT 检索授权 header

python - 带通滤波器ValueError : Digital filter critical frequencies must be 0 < Wn < 1

Python3面向对象编程: Select all objects of a particular class w/o variables