我在python中有一个列表字典,我想检查一个矩阵是否已经存在于dicionary中。
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
我怎么能这样做?
答案 0 :(得分:1)
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
答案 1 :(得分:1)
[[ 8.87155979, 2.50616085]] in [m.tolist() for lst in C.values() for m in lst]
True
答案 2 :(得分:1)
您可以使用两种不同的方式制作它:有和没有列表理解。 with 是" 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]))
答案 3 :(得分:0)
这很好用:
query = [[8.87155979, 2.50616085]]
any(query[0] in x[0] for x in C.values())