python 列出元素序列成员

python list element sequence membership

假设我们有一个参考序列,它是一个列表或元组:

reference = ['a', 'b', 'c', 'd']

我想检查参考序列中是否存在某些序列:

target1 = ['a', 'b', 'c']  # true
target2 = ['a', 'c', 'b']  # false
target3 = ['a', 'c', 'd']  # false
target4 = ['c', 'd', 'e']  # false
target5 = ['c', 'd']       # true

是否有任何内置函数可以检查这种序列成员关系? 谢谢!

第一个想法,你可以将列表或元组转换为字符串,然后查找子字符串是否存在于引用中。一个简单的代码片段来解释我的想法:

reference = ['a', 'b', 'c', 'd']
target1 = ['a', 'b', 'c']  # true

list2str = lambda ref: "".join(ref)

base = list2str(reference)
t1 = list2str(target1)

if t1 in base:
    print 'found'
else:
    print 'unfound'

我找到了相关模块 difflib.SequenceMatcher

def sequence_membership(target, reference):
    get_eq = lambda x: [c for c in x if c[0]=='equal']
    get_length = lambda x: x[2]-x[1]
    s = SequenceMatcher(None, target, reference)
    match_result = s.get_opcodes()
    overlapped = get_eq(match_result)
    if len(overlapped) ==1 and get_length(overlapped[0]) == len(target):
        return True
    else: return False

>>> sequence_membership(target1,reference)
True
>>> sequence_membership(target2,reference)
False
>>> sequence_membership(target3,reference)
False
>>> sequence_membership(target4,reference)
False
>>> sequence_membership(target5,reference)
True