Using Lambda with lists
lambda, python, python-2.7
Solution
Lambdas pretty much doesn't needed here. You can just check it directly:
for table in my_list:
if string in table.Name:
#do stuff
Or using list comprehension, if you want it that way:
if string in [table.Name for table in my_list]:
#do interesting stuff
More efficiently, as @Tim suggested, use a generator expression:
if string in (table.Name for table in my_list):
But if you insist in using lambdas:
names = map(lambda table: table.Name, my_list)
if string in names:
#do amazing stuff!
Here's a little demo:
>>> 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']
Also, avoid using names of built in functions such as `str`, `list` for variable names. It will override them!
Hope this helps!
Problem
I am trying to check if a string object is in a list. Simply written as: ``` if str in list: ``` The problem I am facing is that this list, is not a list of strings, but a list of tables. I understand that nothing is going to happen if I do this comparison directly. What I would like to do is access an attribute of each of these tables called 'Name'. I could create a new list, and do my comparison against that: ``` newList = [] for i in list: newList.append(i.Name) ``` But as I am still a newbie, I am curious about Lambda's and wondered if it would be possible to implement that instead? something like (... but probably nothing like): ``` if str in list (lambda x: x.Name): ```