-1

我正在处理一个填充有以下形式的元组的列表:

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的所有元组:

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

从某种意义上说,是元组列表上的模式匹配。我如何在 Python 中做到这一点?

4

2 回答 2

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)]

ALTERNATIVE:使用匹配任何数字的对象。( __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)]
于 2013-09-30T05:36:41.790 回答
0
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]
于 2013-09-30T05:51:56.407 回答