Python:将所有列表项与字符串的子串进行比较

时间:2013-11-14 04:18:23

标签: python string list

列表中的所有项目都应与字符串的每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 long c在循环期间仅取值为1161

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

2 个答案:

答案 0 :(得分:0)

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

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)

a_str = 'CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA'
print(find_four_substrings(a_str))

返回

set(['CGACA'])

答案 1 :(得分:0)

这将查找长度为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)

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

['CGACA', 'GAAGA']
相关问题