Python 二维列表中列和行的计数num

Python 二维列表中列和行的计数num,python,Python,我有二维阵列: [9, 8, 9, 6, 7, 3, 2, 4, 9] [7, 1, 4, 5, 1, 8, 6, 7, 8] [8, 5, 5, 3, 4, 1, 7, 6, 1] [8, 2, 2, 9, 6, 2, 7, 6, 5] [3, 9, 4, 8, 1, 6, 7, 3, 7] [1, 6, 7, 6, 6, 6, 3, 8, 1] [6, 8, 9, 3, 9, 1, 3, 8, 5] [9, 9, 3, 9, 6, 5, 9, 8, 8] [7, 9, 6, 2, 6, 8,

我有二维阵列:

[9, 8, 9, 6, 7, 3, 2, 4, 9]
[7, 1, 4, 5, 1, 8, 6, 7, 8]
[8, 5, 5, 3, 4, 1, 7, 6, 1]
[8, 2, 2, 9, 6, 2, 7, 6, 5]
[3, 9, 4, 8, 1, 6, 7, 3, 7]
[1, 6, 7, 6, 6, 6, 3, 8, 1]
[6, 8, 9, 3, 9, 1, 3, 8, 5]
[9, 9, 3, 9, 6, 5, 9, 8, 8]
[7, 9, 6, 2, 6, 8, 5, 9, 2] 
例如,我在[0][0]位置上有第9个位置。我想数一数,除了第一个,第[0]行和第[0]列中有多少个9。([n][m])

试试这个:

count = 0
for i in array[0]:
    count += i == 9     #first row
for row in array:
    count += row[0] == 9    #first column

count -= array[0][0] == 9   #if element at [0][0] is 9, we subtract 1 to avoid counting twice
print(count)
此代码将在以下情况下工作:

import numpy as np
arr=[
    [9, 8, 9, 6, 7, 3, 8, 4, 9],
    [7, 8, 4, 5, 8, 8, 6, 7, 8],
    [8, 5, 5, 3, 4, 1, 7, 6, 1],
    [8, 2, 2, 9, 6, 2, 7, 6, 5],
    [3, 9, 4, 8, 1, 6, 7, 3, 7],
    [1, 6, 7, 6, 6, 6, 3, 8, 1],
    [6, 8, 9, 3, 9, 1, 3, 8, 5],
    [9, 9, 3, 9, 6, 5, 9, 8, 8],
    [7, 9, 6, 2, 6, 8, 5, 9, 2],
]
array=np.array(arr)
num=9
solutions = np.argwhere(array == num)
place=solutions[0]
vertical=[]

for i in range(len(arr)):
    vertical.append(arr[i][place[1]])
    
if num in arr[place[0]]:
    one=arr[place[0]].count(num)
    
if num in arr[place[1]]:
    two=vertical.count(num)

#print(one,two)
total=(one+two)-1 # Double counting
print(total)

此答案适用于9以外的任何数字,并且由于使用了numpy模块,因此速度很快???
import numpy as np
arr=[
    [9, 8, 9, 6, 7, 3, 8, 4, 9],
    [7, 8, 4, 5, 8, 8, 6, 7, 8],
    [8, 5, 5, 3, 4, 1, 7, 6, 1],
    [8, 2, 2, 9, 6, 2, 7, 6, 5],
    [3, 9, 4, 8, 1, 6, 7, 3, 7],
    [1, 6, 7, 6, 6, 6, 3, 8, 1],
    [6, 8, 9, 3, 9, 1, 3, 8, 5],
    [9, 9, 3, 9, 6, 5, 9, 8, 8],
    [7, 9, 6, 2, 6, 8, 5, 9, 2],
]
array=np.array(arr)
num=9
solutions = np.argwhere(array == num)
place=solutions[0]
vertical=[]

for i in range(len(arr)):
    vertical.append(arr[i][place[1]])
    
if num in arr[place[0]]:
    one=arr[place[0]].count(num)
    
if num in arr[place[1]]:
    two=vertical.count(num)

#print(one,two)
total=(one+two)-1 # Double counting
print(total)