列表理解python和特定项目

时间:2015-02-07 17:32:34

标签: python python-2.7 list-comprehension

我有一个这样的清单:

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

我想用" a"开始时提取b,c和d。不是" z"并列入一个列表

我无法弄明白该怎么做,有什么建议吗?

3 个答案:

答案 0 :(得分: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']

答案 1 :(得分: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')]
>>> 

答案 2 :(得分: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']