python列表元素序列成员资格

时间:2016-12-08 06:01:35

标签: python 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

是否有内置函数来检查这种序列成员资格? 谢谢!

2 个答案:

答案 0 :(得分:1)

我找到了相关模块FACT: [a-zA-Z](([a-zA-Z0-9] | '.' | '_')*?[a-zA-Z0-9])?;

difflib.SequenceMatcher

答案 1 :(得分:0)

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

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'