繁体   English   中英

在列表中查找连续模式

[英]Finding consecutive patterns in a list

如何使用python查找模式的连续出现? 例如,在['a','b','a','b','c'] ,我们有2个连续的'ab',因此发生了两次。 ['a', 'b', 'a']不包含连续模式。

我写了一个函数,它只能计算模式的发生,而不必连续计数

def get_occur(list, seq):
    return ''.join(list).count(''.join(seq))

我只想指出,如果您实际上是想在字符串中找到重复的模式,则应该使用re buildin

以@Selcuk在评论中所说的为基础,

l = ['a', 'b', 'a', 'b', 'c', 'd']
print(l)

def consec_pattern(lst, pvs):
    # recursively return number of consecutive times pvs (previous pattern)
    # occurs in lst (list)

    if len(lst) < len(pvs):
        return 0 # no occurances of pvs in lst

    if lst[:len(pvs)] == pvs:  # if pvs is found at the start of lst
        shorter = lst[len(pvs):]
        return consec_pattern(shorter, pvs) + 1
    return 0  # if this is not the case, return 0

print(consec_pattern(l, [*'ab']))

# we can now annotate the list with number of occurances
l = [*'xababcd']
print(*l)
for i in range(len(l)):
    # take an element off of l each time you call to find
    # the value for the next position
    print(consec_pattern(l[i:], [*'ab']), end=' ')
print()

如果要特定子列表的连续出现,这是O(n)解决方案,可用于查找所有子列表的出现,但是如果需要所有子列表连续出现,则可能有更有效的方法。

编辑

使用正则表达式库,您可以使用搜索功能

import re
string = 'xababcdab'
pattern = 'ab'

match = re.search(f'({pattern})+', string)
start, end = match.span()
consecutive_matches = (end-start)//len(pattern)
print(consecutive_matches)  # outputs 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM