首页 > 解决方案 > 生成 3 个随机列表并使用它们的元素总和创建另一个

问题描述

我想创建一个 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)

标签: pythonlistmatrix

解决方案


您的问题需要一些评论:

  • 题目与题目不对应,代码与题目相符,与题目不相符;
  • 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]]

推荐阅读