2013-11-20 61 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) 

請注意,理解通常比這個更受歡迎。