Store contigs and genome substrings based on mismatches I have a string, a list of substrings, and a list of positions where substrings are found in string.

string = 'ATGGTACACGCTACGAGCTAG'
substrings = ['TACA', 'CTAGAAAAG']
positions = ['11, 4', '']


Substring 'TACA' appears at positions 11 and 4 in string (i.e. '11, 4').

Substring 'CTAGAAAAG' does not appear in string (i.e. '').

I need to remove 'CTAGAAAAG' from substrings and I need to remove '' from positions, while creating a new list with 'CTAGAAAAG'. I need your help here to create code which will give the following results:

new_substrings = ['TACA']
new_positions = ['11, 4']
new_list = ['CTAGAAAAG']
string = 'ATGGTACACGCTACGAGCTAG' (obtained from above)


Once this is complete, the given code:

new_positions = [map(int, x.split(',')) for x in new_positions]
seq_pos = dict(zip(new_substrings,new_positions))
seq_ref = {k: [string[start:start+length] for start in starts] for k, starts, length in zip(new_substrings,new_positions,[len(x) for x in new_substrings])}


Gives:

seq_pos = {'TACA': [11, 4]}
seq_ref = {'TACA': ['TACG', 'TACA']}


Then, from seq_ref, I need to create a list of integers which represents the number of mismatches between the key: 'TACA' and both of its values: 'TACG' and 'TACA'.

mismatches = [[1, 0]]


The code to find the # of mismatches between two strings is provided:

def HammingDistance(p, q):
    dist = 0
    for i in range(len(p)):
        if p[i] != q[i]:
            dist += 1
    return dist


Finally, I need to save my data in a CSV file (i.e. Excel or Numbers).

new_positions = ['11, 4'] (obtained above)
new_substrings = ['TACA'] (obtained above)
actual_substrings = [['TACG', 'TACA']] (values of seq_ref)
mismatches = [[1, 0]] (obtained above)


Info needs to be sorted based on # of mismatches.



I understand this is a multi-step problem but any help would be appreciated.
For the first question try something like:

new_substrings = []
new_positions = []
new_list = []
for pos, sub in zip(positions, substrings): 
   if not pos:
       new_list.append(sub)
   else:
       new_substrings.append(sub)
       new_positions.append(pos)


this gives:

&gt;&gt;&gt; new_substrings
['TACA']
&gt;&gt;&gt; new_positions
['11, 4']
&gt;&gt;&gt; new_list
['CTAGAAAAG']


For the hamming distance you just need to iterate over the values in seq_ref and append the results of the hamming distance function in mismatches.  Based on the given code and the example above you should be able to create that block.  Below is an untested quick example to get you on track.  

mismatches = []
for seq in seq_ref.keys():
   for value in seq_ref[seq]:
       mismatches.append(HammingDistance(seq, value))


As far as the CSV and sorting is concerned I suggest that you look into pandas or numpy.  Both of those packages provided functions to help with this.