list.append()如何在Python中工作-我得到了意外的结果 [英] How does list.append() work in Python - I'm getting an unexpected result

查看:80
本文介绍了list.append()如何在Python中工作-我得到了意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面编写了以下代码,但其输出与我预期的不一样.有人知道为什么它会这样吗?

I've written the following code below but the output of it is not as I expected. Does anyone know why it is behaving like this?

N.B .:我知道代码不能正确地转置列表-在编写函数时偶然发现了这种奇怪的行为.

N.B.: I know the code doesn't transpose the list correctly - I stumbled across this strange behavior whilst writing the function.

matrix = [
     [1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12],
 ]

transposed = []
for i in range(4):
    print("i", i)
    t_list = []
    for row in matrix:
        print("row", row)
        t_list.append(row[i])
        print("t_list**********", t_list)
        transposed.append(t_list)

        print("transposed//////////////", transposed)

在第一行的末尾,我希望从此函数获得的输出是:

The output I would expect from this function at the end of the first row is:

[[1], [1, 5], [1, 5, 9]]

相反,它似乎输出:

[[1, 5, 9], [1, 5, 9], [1, 5, 9]]

有人知道为什么吗?

谢谢!

推荐答案

重点是制作内部列表的副本,然后追加到外部列表中.

Key point is to make a copy of inner list and then append in the outer list.

copy = t_list [::]

copy = t_list[::]

这是因为list是一个对象,因此是引用.因此,当您在列表中追加另一个项目时,该项目将在该对象存在的所有地方进行更新.对于您的情况,您是将列表追加到列表中,然后更新内部列表,这也会导致以前的列表项也更新.您需要在 transposed 列表中追加列表的副本.这是一个解决方案.

It is because list is an object and it is a refresnce. so when you append another item in a list, it will be updated over all places where that objects exists. In your case, you are appending list into a list and then updating the inner list which causes the previous list items to update as well. You need to append a copy of a list in transposed list. Here is a solution.

transposed = []
for i in range(4):
print("i", i)
t_list = []
for row in matrix:
    print("row", row)
    t_list.append(row[i])
    print("t_list**********", t_list)
    transposed.append(t_list[::])

    print("transposed//////////////", transposed)

这篇关于list.append()如何在Python中工作-我得到了意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆