2013-09-30 30 views
-1

我正在填充表格的元组名单上:如何找到具有特定值的所有元组?

tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776), ...] 

,我想执行两个操作。

首先是要找到开始用数字Ñ的所有元组,例如:

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

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

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

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

回答

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

备选:使用匹配的任何数量的对象。 (__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)] 
+0

哦,真不错,谢谢! – sdasdadas

+2

有趣的替代... –

+0

但我认为第一种方法会更快 –

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] 
相关问题