我想創建一個 NxN 矩陣(表示為串列串列),其中前 n-1 列具有 1 到 10 范圍內的亂數,最后一列包含將先前公共中的數字相加的結果。
import random
randomlist1 = []
for i in range(1,10):
n = random.randint(1,100)
randomlist1.append(n)
print(randomlist1)
randomlist2 = []
for i in range(1,10):
n = random.randint(1,100)
randomlist2.append(n)
print(randomlist2)
randomlist3 = []
for i in range(1,10):
n = random.randint(1,100)
randomlist3.append(n)
print(randomlist3)
# I have problems here
lists_of_lists = [sum(x) for x in (randomlist1, randomlist2,randomlist3)]
[sum(x) for x in zip(*lists_of_lists)]
print(lists_of_lists)
uj5u.com熱心網友回復:
你的問題需要一些評論:
- 題目與題目不相符,代碼與題目相符,與題目不相符;
- 行
randomlist1,randomlist1,randomlist1不在矩陣中; - 最終值不是方陣;
- 您撰寫“列具有 1 到 10 范圍內的亂數”,但您的代碼
randint(1,100)在 [1..100] 范圍內創建數字。
問題的解答
import random
N = 5
# create a N by N-1 matrix of random integers
matrix = [[random.randint(1, 10) for j in range(N-1)] for i in range(N)]
print(f"{N} by {N-1} matrix:\n{matrix}")
# add a column as sum of the previous ones
for line in matrix:
line.append(sum(line))
print(f"{N} by {N} matrix with the last column as sum of the previous ones:\n{matrix}")
輸出:
5 by 4 matrix:
[[7, 10, 5, 6], [4, 10, 9, 3], [5, 5, 4, 9], [10, 7, 2, 4], [8, 8, 5, 3]]
5 by 5 matrix with the last column as sum of the previous ones:
[[7, 10, 5, 6, 28], [4, 10, 9, 3, 26], [5, 5, 4, 9, 23], [10, 7, 2, 4, 23], [8, 8, 5, 3, 24]]
uj5u.com熱心網友回復:
IIUC 嘗試使用 numpy
import numpy as np
np.random.seed(1) # just for demo purposes
# lists comprehensions to create your 3 lists inside a list
lsts = [np.random.randint(1,100, 10).tolist() for i in range(3)]
np.sum(lsts, axis=0)
# array([145, 100, 131, 105, 215, 115, 194, 247, 116, 45])
串列
[[38, 13, 73, 10, 76, 6, 80, 65, 17, 2],
[77, 72, 7, 26, 51, 21, 19, 85, 12, 29],
[30, 15, 51, 69, 88, 88, 95, 97, 87, 14]]
uj5u.com熱心網友回復:
基于@It_is_Chris 的回答,我建議將其作為僅使用 numpy 的實作,而不使用串列:
np.random.seed(1)
final_shape = (3, 10)
lsts = np.random.randint(1, 100, np.prod(final_shape)).reshape(final_shape)
lstsum = np.sum(lsts, axis=0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335431.html
上一篇:如何通過參考列來做條件交叉串列
