Lambdas在这里几乎不需要。你可以只检查它直接:
for table in my_list:
if string in table.Name:
#do stuff
或者使用列表解析,如果你想用那种方式:
if string in [table.Name for table in my_list]:
#do interesting stuff
更有效,因为@Tim建议,用生成器表达式:
if string in (table.Name for table in my_list):
但是,如果你在使用lambda表达式坚持:
names = map(lambda table: table.Name, my_list)
if string in names:
#do amazing stuff!
这里有一个小演示:
>>> class test():
def __init__(self, name):
self.Name = name
>>> my_list = [test(n) for n in name]
>>> l = list(map(lambda table: table.Name, my_list)) #converted to list, it's printable.
>>> l
['a', 'b', 'c']
此外,应避免使用的内置函数的名称,如str
,list
的变量名。它会覆盖它们!
希望这会有所帮助!
lambda功能已经就在那里,你很近! – aIKid