2013-09-30 75 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] 
相關問題