我想创建一个乘法表矩阵

时间:2016-10-10 16:05:43

标签: python python-2.7 python-3.x ipython

我想创建前12个乘法表的矩阵。

到目前为止,我的代码是:

x = range(1,13,1)
n = range(1,13,1)

list_to_append = []
list_for_matrix = []

for i in x:

    for j in n:

        list_to_append.append(i*j)

list_for_matrix.append(list_to_append[0:12])
list_for_matrix.append(list_to_append[12:24])
list_for_matrix.append(list_to_append[24:36])


print (list_to_append)
print (list_for_matrix)

我得到的输出是:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 121, 132, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144]
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24], [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36]]

在我的for循环中,当i=1j = range(1,12,1)时,我希望输出(i*j)作为[1,2,3,4,5,6,7,8,9,10,11,12]之类的列表,这应该在每次迭代时发生。最后,我想将上面的列表附加到一个空列表中     [[1,2,3,4,5,6,7,8,9,,10,11,12]]。所以,在我的代码中,我不能对12个乘法表进行切片。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:5)

您可以使用以下列表理解

x = range(1,13) # default step value is 1, no need to specify
n = range(1,13)

mult_table = [[i*j for j in x] for i in n]

输出:

print(mult_table)
# [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
#  [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
#  [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36],
#  [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48],
#  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60],
#  [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72],
#  [7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84],
#  [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96],
#  [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108],
#  [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
#  [11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 121, 132],
#  [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144]]

注意嵌套的理解,从中生成另一个维度的值,并与第一个维度的值相乘。

答案 1 :(得分:1)

您可以创建一个空列表并向其添加列表。 像:

#!/usr/bin/python
table = []
for y in range(1, 13):
    # Create the inner lists with a temporary variable.
    # You must do this every time before the inner loop is entered,
    # otherwise
    row = []
    # Fill the inner list.
    for x in range(1, 13):
        row.append(x*y)
    # Append the inner list to the outer list.
    table.append(row)
# A much more convenient way would be:
table = [[x*y for x in range(1, 13)] for y in range(1, 13)]
# [f(x) for x in v] is a list of the value of the "f" function for each
# value in the list "v".