python如何迭代生成矩阵_如何在python中迭代矩阵列

您可以为行和列创建一个列表,只需在矩阵上迭代一次,同时将正确的部分相加:

创建解调数据:import random

random.seed(42)

matrix = []

for n in range(10):

matrix.append(random.choices([0,1],k=10))

print(*matrix,sep="\n")

输出:

^{pr2}$

数一数:rows = [] # empty list for rows - you can simply sum over each row

cols = [0]*len(matrix[0]) # list of 0 that you can increment while iterating your matrix

for row in matrix:

for c,col in enumerate(row): # enumerate gives you the (index,value) tuple

rows.append( sum(x for x in row) ) # simply sum over row

cols[c] += col # adds either 0 or 1 to the col-index

print("rows:",rows)

print("cols:",cols)

输出:rows: [4, 5, 5, 9, 2, 4, 6, 4, 5, 6] # row 0 == 4, row 1 == 5, ...

cols: [6, 6, 5, 4, 6, 5, 5, 5, 5, 3] # same for cols

代码更少,但使用zip()对矩阵进行两次完整传递,以转置数据:rows = [sum(r) for r in matrix]

cols = [sum(c) for c in zip(*matrix)]

print("rows:",rows)

print("cols:",cols)

输出:(相同)rows: [4, 5, 5, 9, 2, 4, 6, 4, 5, 6]

cols: [6, 6, 5, 4, 6, 5, 5, 5, 5, 3]

您必须对其进行计时,但是两次完整迭代和压缩的开销可能仍然值得,因为zip()方法继承性比在列表上循环更优化。折衷可能只对某些矩阵尺寸有价值。。。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值