0

我希望乘法函数在 n = 4 时返回此值:

[[1, 2, 3, 4],
 [2, 4, 6, 8],
 [3, 6, 9, 12],
 [4, 8, 12, 16]]

代码:

import numpy

def multiplication_table(n): 
    full_multi = [[]] * n 

    for i in range(n):
        for j in range(n):
            full_multi[i].append( (i+1)*(j+1) )

    list_as_array = numpy.array(full_multi)

    return list_as_array
print(multiplication_table(4))

相反,这是返回(忽略格式):

[

[ 1  2  3  4  2  4  6  8  3  6  9 12  4  8 12 16]

[ 1  2  3  4  2  4  6  8  3  6  9 12  4  8 12 16]

[ 1  2  3  4  2  4  6  8  3  6  9 12  4  8 12 16]

[ 1  2  3  4  2  4  6  8  3  6  9 12  4  8 12 16]

]

我不知道出了什么问题。感谢您的帮助!

4

1 回答 1

1

尝试更改[[] * n][[] for _ n range(n)] 这样:

import numpy

def multiplication_table(n): 
    full_multi = [[] for _ n range(n)] 

    for i in range(n):
        for j in range(n):
            full_multi[i].append((i+1)*(j+1))

    list_as_array = numpy.array(full_multi)

    return list_as_array
print(multiplication_table(4))

这将输出所需的

[[1, 2, 3, 4],
 [2, 4, 6, 8],
 [3, 6, 9, 12],
 [4, 8, 12, 16]]

两个代码不同的原因是复制(在这种情况下是乘法列表)的工作方式。通过这样做[[] * n],您实际上并没有创建n不同的列表,而只是创建n了列表的引用[]

如果我们通过在打印值print之后添加语句来调试代码,我们可以看到以下行为:full_multi[i].append( (i+1)*(j+1))full_multi

[[1], [1], [1], [1], [1]]
[[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]
...

向第一个列表添加一个值也会使其出现在其余列表中,因为它们都引用相同的数据。但是,for循环方法实际上创建了n单独的列表。

有关更多信息,请参见https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/

在 Python(或大多数语言)中复制列表(或任何非原始数据类型)时,您实际上并没有复制数据,而只是创建了一个新引用。

a = 5
b = a  # for primitive data like integers, the value 5 is copied over
a = []
b = a  # only the reference to the list stored in 'a' is copied

a.append(5)
print(a, b)  # will both be the same value since they are the same list, just referenced by 2 different variables

如果您想实际复制列表本身,则必须执行以下操作:

a = []
b = a.copy()  # copies the list, not just the reference

a.append(5)
print(a, b)  # will both be different
于 2021-05-03T18:12:26.543 回答