[英]Searching for a partial match in a list of tuples
如果我們有一個元組列表:
[(0,1),(1,2),(5,5),(4,1)]
如何找到與搜索詞部分匹配的所有項目?
例如,在上面的示例中, (_, 1)
應該與(0, 1)
和(4, 1)
(_, 1)
匹配。
您可以通過使用始終與其他任何對象進行比較的特殊對象來實現通配符匹配。 例如
#!/usr/bin/env python
class Any:
def __eq__(self, other):
return True
def __repr__(self):
return 'Any'
ANY = Any()
#Test
if 1:
print ANY
for v in [1,2,'a', 'b', (2,3,4), None]:
print v, v == ANY
print
def match(target, data):
''' Check that sequence data matches sequence target '''
return len(data) == len(target) and all(u==v for u, v in zip(target, data))
data_list = [(0, 1), (1, 2), (5, 5), (4, 1)]
target = (ANY, 1)
print [v for v in data_list if match(target, v)]
輸出
Any
1 True
2 True
a True
b True
(2, 3, 4) True
None True
[(0, 1), (4, 1)]
感謝Antti Haapala ,這是一個更好的版本,有Any
鴿友。 它輸出與上面的代碼相同的輸出。
#!/usr/bin/env python
class AnyBase(type):
def __eq__(self, other):
return True
def __repr__(self):
return 'Any'
@classmethod
def __subclasscheck__(cls, other):
return True
@classmethod
def __instancecheck__(cls, other):
return True
class Any(object):
__metaclass__ = AnyBase
def __init__(self):
raise NotImplementedError("How'd you instantiate Any?")
#Test
if 1:
print Any
for v in [1,2,'a', 'b', (2,3,4), None]:
print v, v == Any
print
def match(target, data):
''' Check that sequence data matches sequence target '''
return len(data) == len(target) and all(u==v for u, v in zip(target, data))
data_list = [(0, 1), (1, 2), (5, 5), (4, 1)]
target = (Any, 1)
print [v for v in data_list if match(target, v)]
要使用第一個版本,我們確實應該創建該類的實例,但是第二個版本中的Any
類旨在直接使用。 另外,第二個版本顯示了如何處理isinstance
和subclass
檢查。 根據上下文,您可能希望限制這些測試。
new_list = [i for i in old_list if i[1] == 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.