
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
看下如下这个字典
1 | opt_dict = { 'DWord' :[ 'tptU32' , 'tptS32' ], 'Word' :[ 'tptU16' , 'tptS16' ], 'String' : 'tptStr' }
|
确定列表中有没有寻找的元素
1 2 3 4 5 6 7 8 9 10 11 | opt = 'tptU32'
opt_str = 'tptStr'
opt_int = 10
opt_dict = { 'DWord' :[ 'tptU32' , 'tptS32' ], 'Word' :[ 'tptU16' , 'tptS16' ], 'String' : 'tptStr' , 'dataint' :[10,3]}
for key, val in opt_dict.items():
if opt in val:
print (key)
if opt_str in val:
print (key)
if str(opt_int) in str(val):
print (key)
|
如上所示,然后输出如下:
1 2 3 4 5 6 | H:\python3.7.6\python.exe H:/test_project/test.py
DWord
String
dataint
Process finished with exit code 0
|
可以看见,无论字典的值是否为单个多个,是否以列表还是单纯字符串,都可以使用in来进行判断,并准确返回key值。
这里是否发现了有个int型的,因为int是不可以使用in来判断的,所以要先转为str在进行寻找,当然了如果你对这种方式的返回值不满意的话,可以在根据需要进行下类型转换,谁叫python这么随便这么强大呢。