检查矩阵是否在字典中

2022-12-01 03:35:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python列表字典,我想检查一个矩阵是否已经在字典中了。你知道吗

C = {0: [matrix([[ 8.87155979,  2.50616085]]), matrix([[ 0.46289077,  8.05592104]])], 
     1: [matrix([[-1.3115368 ,  7.60922069]])], 
     2: [matrix([[ 0.46289077,  8.05592104]]), matrix([[-1.3115368 ,  7.60922069]]), matrix([[ 3.4826805 , -0.73544937]])]}

此输入应返回true[[ 8.87155979, 2.50616085]] in C 我该怎么做?你知道吗


Tags: intrue列表字典矩阵matrix
3条回答
C= {0: [[[ 8.87155979, 2.50616085]],[[ 0.46289077, 8.05592104]]], 1: [[[-1.3115368 , 7.60922069]]]}

y = [[ 8.87155979,  2.50616085]]
print  any(y in x for x in C.values())# checks the subelements of the values in your dict
True

这将根据你的例子为你的矩阵工作。你知道吗

y=[[ 0.46289077,  8.05592104]]

C = {0: [matrix([[ 8.87155979,  2.50616085]]), matrix([[ 0.46289077,  8.05592104]])],
     1: [matrix([[-1.3115368 ,  7.60922069]])],
     2: [matrix([[ 0.46289077,  8.05592104]]), matrix([[-1.3115368 ,  7.60922069]]), matrix([[ 3.4826805 , -0.73544937]])]}



 print any((y == x[0]).all() for x in C.values())
 True
[[ 8.87155979, 2.50616085]] in [m.tolist() for lst in C.values() for m in lst]
True

你可以使用两种不同的方法:有列表理解和没有列表理解。使用是“python方式”,但这取决于您的决定:

from numpy import *

C = {0: [matrix([[ 8.87155979,  2.50616085]]), matrix([[ 0.46289077,  8.05592104]])], 
     1: [matrix([[-1.3115368 ,  7.60922069]])], 
     2: [matrix([[ 0.46289077,  8.05592104]]), matrix([[-1.3115368 ,  7.60922069]]), matrix([[ 3.4826805 , -0.73544937]])]}

y = [[ 8.87155979, 2.50616085]]

# without list comprehension
for x in C.values():
    for m in x:
        if all(m==y):
            print(True)

# with list comprehension
print(any([all(m==y) for x in C.values() for m in x]))