Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中的列表中添加列表_Python - Fatal编程技术网

在python中的列表中添加列表

在python中的列表中添加列表,python,Python,我是编程新手,并且试图理解语法 在我的示例中,我希望得到以下结果:table=[[1,2,3],[2,4,6],[3,6,9]] 但不知怎的,我得到了一张空名单。我不知道在哪里修理它 row = [1, 2, 3] col = [1, 2, 3] li = [] table = [] for x in row: for n in col: li.append(x*n) table.append(li) li.clear() print(table) 在

我是编程新手,并且试图理解语法

在我的示例中,我希望得到以下结果:table=[[1,2,3],[2,4,6],[3,6,9]] 但不知怎的,我得到了一张空名单。我不知道在哪里修理它

row = [1, 2, 3]
col = [1, 2, 3]
li = []
table = []
for x in row:
    for n in col:
        li.append(x*n)
    table.append(li)
    li.clear()

print(table)

在引擎盖下,列表是指针。这意味着,当您将一个列表附加到另一个列表时,它不是在创建新列表,而是在使用同一个列表。 因此,无论何时执行
li.clear
,它都会删除内部列表元素

你会想要这个的

row = [1, 2, 3]
col = [1, 2, 3]
table = []
for x in row:
    li = []
    for n in col:
        li.append(x*n)
    table.append(li)

print(table)
每次创建一个新的列表,以便它在内存中成为一个单独的对象,用于使用自己的代码执行每个
append
操作

row = [1, 2, 3]
col = [1, 2, 3]
table = []
for x in row:
    li = []
    for n in col:
        li.append(x*n)
    table.append(li)

print(table)
然后您将获得:

行=[1,2,3]
col=[1,2,3]
表=[]
对于第行中的x:
li=[]
对于n列:
li.追加(x*n)
表1.追加(li)

不同之处在于将
li=[]
变量放在for循环的第一级中。这基本上每次都会“清除”它。

您需要了解python中什么是mutabe和不可变的

让我简单地解释一下代码中发生了什么

row = [1, 2, 3]
col = [1, 2, 3]
li = []
table = []
for x in row:
    for n in col:
        li.append(x*n)
    table.append(li) # everything is good until here
    li.clear() # but here you are sayning that li is empty so it also goes and changes table.append(li) to table.append(li.clear()), because li is a list and lists are mutable objects. 
# what you can do is create another new object (which happens to be named li: li=[] so the table.append(li) will not change to table.append([])
将代码更改为

row = [1, 2, 3]
col = [1, 2, 3]
li = []
table = []
for x in row:
    for n in col:
        li.append(x*n)
    table.append(li)
    li = []

print(table)

为什么要执行
li.clear()
table.append(li[:])
-如果清除要附加到表中的同一个列表,显然最终会得到
[]
。附加副本instead@yatu,他这样做是为了得到所描述的输出,而不是:
[[1,2,3],[1,2,3,2,4,6],[1,2,3,2,4,6,3,6,9],
答案是正确的,但如果你解释它为什么会起作用,它会更有帮助。投票不仅提供解决方案,而且提供解释。我的思考过程实际上就是代码的流程,我不知道clear仍然会影响上半部。我想我对clear的理解还不够。