如何找到具有特定值的所有元组?

sda*_*das -1 python tuples list pattern-matching

我正在使用以下形式的元组填充的列表:

tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776), ...]
Run Code Online (Sandbox Code Playgroud)

我想执行两个操作.

第一个是查找以数字n开头的所有元组,例如:

def starting_with(n, tups):
    '''Find all tuples with tups that are of the form (n, _, _).'''
    # ...
Run Code Online (Sandbox Code Playgroud)

第二个是相反的,找到第二个值为n的所有元组:

def middle_with(n, tups):
    '''Find all tuples with tups that are of the form (_, n, _).'''
    # ...
Run Code Online (Sandbox Code Playgroud)

从某种意义上说,在元组列表上进行模式匹配.我如何在Python中执行此操作?

fal*_*tru 5

使用列表理解:

>>> 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)]
Run Code Online (Sandbox Code Playgroud)

替代方法:使用与任意数字匹配的对象.(__eq__)

>>> 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)]
Run Code Online (Sandbox Code Playgroud)