2013-11-20 25 views
4

我想检查一个字符串对象是否在列表中。简写为:在列表中使用Lambda

if str in list: 

我面对的问题是这个列表不是一个字符串列表,而是一个表列表。我明白,如果我直接进行这种比较,没有什么会发生。我想要做的是访问这些名为'名称'的每个表的属性。

我可以创建一个新的列表,并尽我针对比较:

newList = [] 
for i in list: 
    newList.append(i.Name) 

但是,当我还是一个新手,我很好奇LAMBDA的,并想知道,是否有可能实现呢?

像(...但可能没有像):

if str in list (lambda x: x.Name): 
+0

lambda功能已经就在那里,你很近! – aIKid

回答

3

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'] 

此外,应避免使用的内置函数的名称,如strlist的变量名。它会覆盖它们!

希望这会有所帮助!

+2

如果有大量的表,应该使用生成器表达式而不是列表理解。 – Tim

+0

太棒了!我也喜欢列表理解的例子。非常有帮助...干杯 – iGwok

+0

@iGwok没问题!如果您愿意,请接受它:D – aIKid

2

您可以使用过滤器

>>> foo = ["foo","bar","f","b"] 
>>> list(filter(lambda x:"f" in x,foo)) 
['foo', 'f'] 

更新

我保留这个答案,因为可能有人会来这里对于lambda,但对于这个问题@arbautjc的回答更好。

6

你可以写

if str in [x.Name for x in list] 

或者更懒惰,

if str in (x.Name for x in list) 

在后者(带括号),它建立了一个发电机,而在前者(带支架),它建立第一完整列表。

+0

这很好用...谢谢 – iGwok

+0

@iGwok你应该接受答案 –

3

我猜你正在寻找any

if any(x.Name == s for x in lst): 
    ... 

如果该列表不是很大,你需要这些名称在其他地方,你可以创建一个列表或一组名称:

names = {x.Name for x in lst} 
if s in names: 
    .... 

你写的拉姆达已经在蟒蛇,并呼吁attrgetter(模块operator):

names = map(attrgetter('Name'), lst) 

请注意,理解通常比这个更受欢迎。