Python 如何查找具有特定值的所有元组?
我正在处理一个填充了元组的列表:Python 如何查找具有特定值的所有元组?,python,list,pattern-matching,tuples,Python,List,Pattern Matching,Tuples,我正在处理一个填充了元组的列表: tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776), ...] 我想做两个手术 第一个是查找以数字n开头的所有元组,例如: def starting_with(n, tups): '''Find all tuples with tups that are of the form (n, _, _).''' # ... 第二个是相反的,找到第二个值为n的所有元组: 从某种意义上说,模式匹配依赖于元
tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776), ...]
我想做两个手术
第一个是查找以数字n开头的所有元组,例如:
def starting_with(n, tups):
'''Find all tuples with tups that are of the form (n, _, _).'''
# ...
第二个是相反的,找到第二个值为n的所有元组:
从某种意义上说,模式匹配依赖于元组列表。如何在Python中实现这一点?使用列表理解:
>>> tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776)]
>>> [t for t in tups if t[0] == 1] # starting_with 1
[(1, 2, 4.56), (1, 3, 2.776)]
>>> [t for t in tups if t[1] == 3] # (_, 3, _)
[(1, 3, 2.776)]
备选方案:使用与任意数字匹配的对象
但我认为第一种方法会更快
>>> tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776)]
>>> [t for t in tups if t[0] == 1] # starting_with 1
[(1, 2, 4.56), (1, 3, 2.776)]
>>> [t for t in tups if t[1] == 3] # (_, 3, _)
[(1, 3, 2.776)]
>>> class AnyNumber(object):
... def __eq__(self, other):
... return True
... def __ne__(self, other):
... return False
...
>>> ANY = AnyNumber()
>>> ANY == 0
True
>>> ANY == 1
True
>>> tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776)]
>>> [t for t in tups if t == (1, ANY, ANY)]
[(1, 2, 4.56), (1, 3, 2.776)]
>>> [t for t in tups if t == (ANY, 1, ANY)]
[(2, 1, 1.23)]
def starting_with(n, tups):
'''Find all tuples with tups that are of the form (n, _, _).'''
return [t for t in tups if t[0] == n]