簡體   English   中英

我想創建一個二維列表,其行和列作為輸入,其元素是行號和列號的乘積

[英]I want to create a 2d list with its rows and columns taken as input and its elements being the product of row and column numbers

這是我編寫的代碼,但我無法找到將列表中的值更改為行號和列號的乘積的方法

r = int(input("Input number of rows: "))
c = int(input("Input number of columns: "))
multi_list = [[1 for col in range(1, c+1)] for row in range(1, r+1)]

for row in range(1, r):
    for col in range(1,r):
        multi_list[row][col] = r*c

for inner_list in multi_list:
    for val in inner_list:
        print(val, end=' ')
    print()

你在這里有兩個選擇,

  1. 列表理解。
  2. for 循環。

列表理解解決方案:

row = int(input("Input number of rows: "))
col = int(input("Input number of columns: "))
#        [[        COL                   ]       ROW                 ]
matrix = [[r*c for c in range(1, col + 1)] for r in range(1, row + 1)]

讓我們假設 2 行和 5 列
1 . 列表理解:

from pprint import pprint
row, col = 2, 5
matrix = [[r*c for c in range(1, col + 1)] for r in range(1, row + 1)]
pprint(matrix, indent=4, width=25)
[   [1, 2, 3, 4, 5],
    [2, 4, 6, 8, 10]]

2 . 另一個選項是 for 循環:

from pprint import pprint
row, col = 2, 5

matrix = []
for r in range(1, row + 1):
    m.append([])  # add new row
    for c in range(1, col + 1):
        m[c-1].append(r*c)
        # m[-1].append(r*c)  # this will work too.

pprint(matrix, indent=4, width=25)
[   [1, 2, 3, 4, 5],
    [2, 4, 6, 8, 10]]

您的第一個循環必須更正為:

for row in range(1, r+1):
    for col in range(1,c+1):
        multi_list[row-1][col-1] = row*col

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM