问题
I have the following code:
for k, (j,k) in enumerate (zip(line1_u,line2_u_rev_comp)):
if j==k:
Match1+=1
if j== 'N' or k == 'N':
Unknown1+=1
if j != k:
Different1+=1
This takes 2 lines (line1_u and line2_u_rev_comp) and compares them character by character to identify if they match, have an N which places it in the unknown category or are different. What I want is as well as tallying up each of these is to identify if 10 characters or more in a row match. How could this be done? Explanation of code would be greatly appreciated.
回答1:
You should look into itertools.groupby:
from collections import defaultdict
from itertools import groupby
def class_chars(chrs):
if 'N' in chrs:
return 'unknown'
elif chrs[0] == chrs[1]:
return 'match'
else:
return 'not_match'
s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
n = 0
consec_matches = []
chars = defaultdict(int)
for k, group in groupby(zip(s1, s2), class_chars):
elems = len(list(group))
chars[k] += elems
if k == 'match':
consec_matches.append((n, n+elems-1))
n += elems
print chars
print consec_matches
print [x for x in consec_matches if x[1]-x[0] >= 9]
Output:
defaultdict(<type 'int'>, {'not_match': 4, 'unknown': 1, 'match': 23})
[(0, 9), (14, 23), (25, 27)]
[(0, 9), (14, 23)]
回答2:
Have a look at the difflib module in python: https://docs.python.org/2/library/difflib.html. Use find_longest_match
to find the longest common subsequence.
来源:https://stackoverflow.com/questions/23548091/identify-short-sequences-of-matches-between-2-strings