[英]How can I find if a function is in the list (Python)
我有一个已保存但未运行的功能列表 。
我需要遍历此列表,并查看列表中是否存在我要查找的项目之一。
我怎样才能做到这一点?
这是函数的存储方式。
self.pysat_fun.set_fun_list(self.pysat_fun.set_file_outpath) # add this function to the pysat list to be run
def set_fun_list(self, fun, replacelast=False):
if replacelast:
self.fun_list[-1] = fun
else:
self.fun_list.append(fun)
这是我的尝试。
for i in range(0, len(self.fun_list)):
if pysat_func.do_norm in self.fun_list:
print("True")
for i in range(self.leftOff, len(self.fun_list)):
if pysat_func.do_norm == self.fun_list [i]:
print("True")
break
或者,简短地:
print (pysat_func.do_norm in self.fun_list [self.leftOff : ])
其工作原理如下:
self.fun_list
是要在其中搜索功能的列表。
self.fun_list [self.leftOff : ]
是该列表的尾部,因为从您的原始代码来看,您似乎只想从索引为self.leftOff
元素中进行搜索。
[self.leftOff : ]
称为切片,:后面的空格表示“直到结束”。
pysat_func.do_norm in aList
是一个布尔表达式,当且仅当pysat_func.do_norm
在aList
,该表达式的值为True
所以
pysat_func.do_norm in self.fun_list [self.leftOff : ]
是一个布尔表达式,当且仅当pysat_func.do_norm
在我所说的尾巴中时,该表达式的值为True
print (anyThing)
将在其括号内打印任何内容,恰好是上述的True
(或False
)。
特定列表中哪些绑定方法不存在的示例:
class A:
def f (self):
print ('f')
def g (self):
print ('g')
a1 = A ()
a2 = A ()
aList = [a1.f, a2.g]
print (
a1.f in aList,
a1.g in aList,
a2.f in aList,
a2.g in aList
)
印刷品:
True False False True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.