2015-10-25 33 views
-2

我有一個Python列表,看起來像這樣:過濾Python列表

myarray = [('31.10', 'John', 'Smith', 'ZK'),('01.11', 'John', 'Smith', 'OK'),('31.10', 'John', 'Doe', 'ZK'),('01.11', 'John', 'Doe', 'ZK')] 

我想用2個鍵來進行過濾。 2個名稱鍵。

ex。過濾myarray中包含John和能源部獲得:

01.11 John Doe ZK 
31.10 John Doe ZK 
+0

你有一個包含元組的列表。你有沒有嘗試過自己呢? –

+0

我嘗試了許多不同的結果=過濾器(lambda x:x [0]是「Doe」,myarray),但我甚至不能用一個鍵過濾它。 輸出結果只有[] – John

+1

那麼你在這種情況下輸出的結果是什麼?請在你的問題中添加這個內容,它有助於構建上下文,並讓我們知道你已經知道了多少。你可以[編輯]它。 –

回答

0

這裏有原則很好的討論: List filtering: list comprehension vs. lambda + filter

稍微使其適應於您的問題:

def filterbyvalue(seq, position, value): 
    for el in seq: 
     if el[position]==value: yield el 

myarray = [('31.10', 'John', 'Smith', 'ZK'),('01.11', 'John', 'Smith', 'OK'),('31.10', 'John', 'Doe', 'ZK'),('01.11', 'John', 'Doe', 'ZK')] 

results = filterbyvalue(myarray, 2, "Doe") 
for x in results: 
    print(x) 

的filterbyvalue函數返回一個生成器,它可以被稱爲正常。

+0

這對我有用。非常感謝你 – John

0

你需要在列表中,以測試每個元組:

for entry in myarray: 
    if entry[1:3] == ('John', 'Doe'): 
     print ' '.join(entry) 

我用切片只選擇在指數12零件那裏,但你也可以使用元組拆包:

for num1, first, last, token in myarray: 
    if (first, last) == ('John', 'Doe'): 
     print num1, first, last, token 

,或者如果元組的平等還沒有清晰你做什麼的,用不同的比較和and

for num1, first, last, token in myarray: 
    if first == 'John' and last == 'Doe': 
     print num1, first, last, token