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