列表理解 python 和特定项目
List comprehension python and specific item
我有一个这样的列表:
list_input = [(a,b), (a,c), (a,d), (z,b), (z,e)]
我想在使用 "a" 而不是 "z" 启动时提取 b、c 和 d 并放入列表中
我不知道该怎么做,有什么建议吗?
根据第一个值过滤列表项,收集第二个值:
[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']
或者;
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')]
>>>
您也可以明确地这样做:
In [8]: [list_input[i][1] for i in xrange(len(list_input)) if list_input[i][0] =='a']
Out[8]: ['b', 'c', 'd']
我有一个这样的列表:
list_input = [(a,b), (a,c), (a,d), (z,b), (z,e)]
我想在使用 "a" 而不是 "z" 启动时提取 b、c 和 d 并放入列表中
我不知道该怎么做,有什么建议吗?
根据第一个值过滤列表项,收集第二个值:
[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']
或者;
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')]
>>>
您也可以明确地这样做:
In [8]: [list_input[i][1] for i in xrange(len(list_input)) if list_input[i][0] =='a']
Out[8]: ['b', 'c', 'd']