python - 生成 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)
解决方案
您的问题需要一些评论:
- 题目与题目不对应,代码与题目相符,与题目不相符;
- 行
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]]
推荐阅读
- android - 使用 Kotlin 中的导体库进行退出确认
- python - 按钮形成一个 tkinter 窗口,出现在另一个 tkinter 窗口上
- http2 - Deno 1.9 原生网络服务器 API 和方法?
- object - Odoo 12 - 创建对字段的依赖
- python - SQLAlchemy 正确处理死锁
- javascript - 我正在尝试将我的几何图形转换为 GeoJSON 格式,以便可以将其导入地理服务器。我收到以下错误
- ruby - 使用 Nokogiri xpath 解析时未插入 Ruby 环境变量
- python - 将对象数组中的元素从 int 转换为 float python numpy
- laravel - 如何在 Laravel Fortify 中进行身份验证后运行自定义代码?
- r - 在 streem_tweet 请求 rtweet 中使用布尔值