Python:比较所有列表项到字符串的子字符串

2024-09-24 22:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

列表中的所有项都应该与字符串中每50个长的子字符串进行比较。我写的代码可以处理较小的字符串长度,但是如果字符串非常大(例如:8800),则不会。有人能提出更好的方法或调试代码吗?在

代码:

a_str = 'CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA'
a = 0
b = 5
c = 50
leng = len(a_str)
lengb = leng - b + 1
list1 = []
list2 = []
list3 = []
list4 = []
for i in a_str[a:lengb]:
    findstr = a_str[a:b]
    if findstr not in list2:
        count = a_str.count(findstr)
        list1 = [m.start() for m in re.finditer(findstr, a_str)]
        last = list1[-1]
        first = list1[0]
        diff = last - first
        if diff > 45:
            count = count - 1
        if count > 3:
            list2.append(findstr)
            list3.append(list1)
    a += 1
    b += 1

a = 0
dictionary = dict(zip(list2, list3))
for j in list2:
    for k in a_str[a:c]:
        if c < leng:
            str1 = a_str[a:c]
            if str1.count(j) == 4:
                list4.append(j)
    a += 1
    c += 1

print(list4)

对于长度为8800、b=10、count1=17和c=588的字符串,在循环过程中,c的值只到1161

我需要长度为5的子串在50的窗口中重复4次(即:主字符串的每50个字符)


Tags: 字符串代码inforifcountappendstr
2条回答

我使用理解和集合来创建一个更易于理解的函数。在

def find_four_substrings(a_str, sub_len=5, window=50, occurs=4):
    '''
    Given a string of any length return the set of substrings
    of sub_length (default is 5) that exists exactly occurs 
    (default 4) times in the string, for a window (default 50)
    '''
    return set(a_str[i:i+sub_len] for i in range(len(a_str) - sub_len) 
                if a_str.count(a_str[i:i+sub_len], i, window) == occurs)

以及

^{pr2}$

退货

set(['CGACA'])

这将查找长度为5且在50个字符内重复至少4次或更多次(不重叠)的所有子字符串。结果列表没有重复项。在

a_str = 'CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA'
b = 5      #length of substring
c = 50     #length of window
repeat = 4 #minimum number of repetitions

substrings = list({
    a_str[i:i+b]
    for i in range(len(a_str) - b)
    if a_str.count(a_str[i:i+b], i+b, i+c) >= repeat - 1
})
print(substrings)

我相信这就是你想要的。如果不是,请告诉我。在

^{pr2}$

相关问题 更多 >