2010-04-23 79 views
4

測試集合中是否存在以另一個元組開頭的元組的測試方法是什麼?其實,我真的很匹配的索引之後,但我也許可以從測試例子Python,使用部分匹配測試集合中成員身份的簡明方法

搞清楚例如:

c = ((0,1),(2,3)) 
# (0,) should match first element, (3,)should match no element 

我要補充我的Python 2.4和/或2.5

感謝

回答

3

編輯: 感謝OP對問題的補充說明。
S.Mark's nested list comprehensions是相當邪惡的;檢查他們。

我可能會選擇使用的輔助功能:

def tup_cmp(mytup, mytups): 
    return any(x for x in mytups if mytup == x[:len(mytup)]) 

>>> c = ((0, 1, 2, 3), (2, 3, 4, 5)) 
>>> tup_cmp((0,2),c) 
False 
>>> tup_cmp((0,1),c) 
True 
>>> tup_cmp((0,1,2,3),c) 
True 
>>> tup_cmp((0,1,2),c) 
True 
>>> tup_cmp((2,3,),c) 
True 
>>> tup_cmp((2,4,),c) 
False 

原來的答覆:
使用是否爲你list-comprehension工作?:

c = ((0,1),(2,3)) 

[i for i in c if i[0] == 0] 
# result: [(0, 1)] 

[i for i in c if i[0] == 3] 
# result: [] 

列表譜曲是introduced in 2.0

+0

是的組合,這個對我有用。不過,我真的很想知道如何比較元組,而不是單個成員,例如'(0,1,2)==(0,1,2,3)[:len(((0,1,2)))]'(似乎不pythonic) – Anycorn 2010-04-23 05:54:06

2
>>> c = ((0,1),(2,3)) 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,),x))] 
[(0, 1)] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,1),x))] 
[(0, 1)] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,),x))] 
[(2, 3)] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,3),x))] 
[(2, 3)] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((4,),x))] 
[] 

有了較大的元組

>>> c=((0,1,2,3),(2,3,4,5)) 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,1),x))] 
[(0, 1, 2, 3)] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,2),x))] 
[] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,),x))] 
[(2, 3, 4, 5)] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,3,4),x))] 
[(2, 3, 4, 5)] 
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((4,),x))] 
[] 
>>> 

編輯:更緊湊的人會

>>> [x for x in c if all(len(set(y))==1 for y in zip((0,),x))] 
[(0, 1, 2, 3)] 
+0

沒問題,稍作修改'[x對於x in c if(len(set(y))爲1的y(in zip((0,),x))]' – Anycorn 2010-04-23 06:06:52

+0

哦,我剛剛也貼出了類似的@aaa == 1,可能是2空間減少 – YOU 2010-04-23 06:07:40

1

自己的解決方案,其他兩個答案

f = lambda c, t: [x for x in c if t == x[:len(t)]] 
+0

+1回答你自己的問題:-)並感謝您擴大您的問題。我在回答中發佈了類似的內容。 – bernie 2010-04-23 07:00:16

相關問題