gpt4 book ai didi

python - 在python中查找矩阵行的变化

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:14 25 4
gpt4 key购买 nike

我有一个用 0 和 1 编码的 NxM 矩阵 - 其中只有 1 要打印在其各自的位置,而 0 是空格,例如以下矩阵:

 m = [[0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0]
[1 1 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1]

我的问题是如何从每一行中从 0 到 1 发生的变化创建起点,并从从 1 到 0 发生的变化创建终点。然后打印起点和终点之间所有的1

我有以下代码(不起作用):

nrows, ncols = m.shape #gets the shape of the matrix
for r in range(nrows):
for c in range(ncols):
if m[r,c] == 0 and m[r,c+1] == 1: #checks if there is a 0 first and then a 1 in the next index of the column in the row to create a starting point
start = m[r,c+1]
if m[r,c] == 1 and m[r,c+1] == 0: #checks if there is a 1 first and then a 0 in the next index of the column in the row to create an end point
end = m[r, c+1]

我想要的输出是,例如考虑最后一行:

It should print everything between the first 1 and last 1 before a 0 is found in that row, excluding the 0s. So basically this: 1 1 1 1....1 1 1 1 1 1....1 1 The dots (.)represent the 0s that have to be excluded All help and advice will be highly appreciated.

最佳答案

您的目标是打印输出还是指示 1 开始和结束位置的标记?如果您的目标只是打印输出,为什么不做一些简单的事情,例如:

m = [[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1]
]

for row in m:
for bit in row:
print(bit or ' ', end=' ')
print()

输出

              1 1 1 1                   
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1

按照您认为合适的方式进行操作,以消除零的空格或 1 之间的空格(即 ' ' 空格与 '' 空字符串。)

Do you mind showing/explaining on how I am able to get the markers where the 1s begin and end?

借用 Identify groups of continuous numbers in a list 的 SO 答案,我们可以这样做:

for row in m:
indicies = compress(count(), row)

ranges = []

for _, g in groupby(enumerate(indicies), lambda x: x[0] - x[1]):
group = [x[1] for x in g]
ranges.append((group[0], group[-1]))

print(ranges)

输出

[(7, 10)]
[(7, 10)]
[(5, 8)]
[(5, 8)]
[(14, 17)]
[(14, 17)]
[(0, 3), (8, 13), (18, 19)]

关于python - 在python中查找矩阵行的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44074431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com