2015-02-07 86 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