Python 和矩阵

标签 python python-2.7 matrix

我有以下矩阵:

W = [['a', 'b', 'b', 'b', 'a'],
     ['a', 'a', 'a', 'a', 'b'],
     ['a', 'b', 'a', 'b', 'b'],
     ['a', 'a', 'a', 'b', 'b'],
     ['b', 'b', 'b', 'b', 'b'],
     ['b', 'b', 'b', 'b', 'b']]

如果我从矩阵中选择 W[x][y],如何计算该特定点周围的 a 字符?例如,假设我选择 W[4][1],即 b。我可以看到该点周围有三个 a。但如何通过编码来确定呢?我最终得到了非常困惑的代码,并意识到如果我们改变矩阵的维度,它就不会起作用。问题还在于,如果我选择靠近回合的点,W[y-1][(x):(x+1)].count("a") -这种思维不会工作。

再次感谢您的帮助!谢谢!

更新:

W     = [['K', ' ', ' ', ' ', ' '],
         ['K', 'K', 'K', 'K', ' '],
         ['K', ' ', 'K', ' ', ' '],
         ['K', 'K', 'K', ' ', ' '],
         [' ', ' ', ' ', ' ', ' '],
         [' ', ' ', ' ', ' ', ' ']]

def count_matrix(W, y, x, ch="K"):
    ref = (-1, 0, 1)
    occ = []
    a = "K"
    b = " "
    for dy, dx in [(a, b) for a in ref for b in ref if (a,b)!=(0, 0)]:
        if (x+dx) >= 0 and (y+dy) >= 0:
            try:
                occ.append(W[x+dx][y+dy])
            except IndexError:
                pass
    return occ.count(ch)
print count_matrix(W,0,0)

这将返回0

最佳答案

这有效:

W = [['a', 'b', 'b', 'b', 'a'],
     ['a', 'a', 'a', 'a', 'b'],
     ['a', 'b', 'a', 'b', 'b'],
     ['a', 'a', 'a', 'b', 'b'],
     ['b', 'b', 'b', 'b', 'b'],
     ['b', 'b', 'b', 'b', 'b']]

def count_matrix(W, r,c, ch):
    ref=(-1,0,1)
    matches=[]
    for dr, dc in [(a, b) for a in ref for b in ref if (a,b)!=(0,0)]:
        if r+dr>=0 and c+dc>=0:
            try:
                matches.append(W[r+dr][c+dc])
            except IndexError:
                pass
    return matches.count(ch)

print count_matrix(W,0,0,'a')   # correctly handles upper LH 
# 2
print count_matrix(W,4,1,'a') 
# 3

如果您想计算方 block 本身的字符数,请删除if (a,b)!=(0,0)。即,对于正方形0,0,你是否数过那里的“a”?

关于Python 和矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19736647/

相关文章:

python xml : xpath for elements with childer with specific attribute values

python - 使用 BeautifulSoup 添加元标记

c++ - 矩阵乘法速度问题

MATLAB:像波前算法一样制作矩阵

从字符串创建自定义矩阵

Python Lambda 可变性

python - 线程启动后如何更改其特性?

python - 优化遍历每个元素的 NumPy 矩阵总和

python - 我怎样才能打破这一行来满足 PEP8 要求?

python-2.7 - 使用 xarray 读取多个坐标