2015-02-07 69 views
0

我有一個這樣的名單:列表理解Python和具體項目

list_input = [(a,b), (a,c), (a,d), (z,b), (z,e)] 

我想提取b,c和d時啓動「一」不與「Z」,並把在列表

我想不出如何去做,有什麼建議?

+0

這不是一個列表理解。你有一個正常的名單;這裏沒有涉及'for'循環。 – 2015-02-07 17:34:28

回答

5

過濾器上的第一個值列表項,收集第二:

[second for first, second in list_input if first == 'a'] 

演示:

>>> list_input = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('z', 'b'), ('z', 'e')] 
>>> [second for first, second in list_input if first == 'a'] 
['b', 'c', 'd'] 
+0

謝謝Martijn的幫助 – 2015-02-08 04:06:59

0

;或

list_input = [("a","b"), ("a","c"), ("a","d"), ("z","b"), ("z","e")] 

print ([x[1] for x in list_input if x[0]=="a"]) 

>>> 
['b', 'c', 'd'] 
>>> 

用索引操縱它。您也可以顯示該特定對;

print ([(x,x[1]) for x in list_input if x[0]=="a"]) 

輸出;

>>> 
[(('a', 'b'), 'b'), (('a', 'c'), 'c'), (('a', 'd'), 'd')] 
>>> 
+0

謝謝howaboutNO – 2015-02-08 04:05:40

0

你也可以做到這一點明確:

In [8]: [list_input[i][1] for i in xrange(len(list_input)) if list_input[i][0] =='a'] 
Out[8]: ['b', 'c', 'd'] 
+0

我會建議可用的選項,你這樣做@ Martijn的方式。這是最好的。我剛剛發佈了這個向你展示了另一種方式來做到這一點...蟒蛇的力量:P – 2015-02-07 17:42:00

+0

謝謝Abhinav – 2015-02-08 04:04:55