根据条件过滤元组列表 [英] Filter a list of tuples based on condition
本文介绍了根据条件过滤元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表:
A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]
此列表的每个成员都是这样的:(数字,字符串)
Each member of this list is like this: (number, string)
现在,如果我要选择大于2的成员并编写字符串,该怎么办?
Now if I want to select the members if the number is bigger than 2 and write the string, what should I do?
例如:
选择数字大于2的成员,输出应为:'K','J'
For example:
selecting the member with a number bigger than 2. the output should be: 'K','J'
推荐答案
使用列表理解:
[y for x,y in A if x>2]
演示:
>>> A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]
>>> [y for x,y in A if x>2]
['K', 'J']
>>>
这篇关于根据条件过滤元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文