Jessi
Jessi

Reputation: 1468

Getting positional difference between two strings within the lists python

I'm trying to find out the positional difference between two strings within two different lists. The code that I've been trying is..

a = ['ATG','TGA','CCC','GCT','TGA']

b = ['TCG','TGA','CCG','GCA','TGA']

for i,j in enumerate(a):
    if j != b[i]:
       print i,j,b[i]

This code generates,,,

0 ATG TCG
2 CCC CCG
3 GCT GCA

I know how to get the difference between two lists, but my desired result is..

 ATG TCG TC*
 CCC CCG **G
 GCT GCA **A

Basically, I want to print out the positional differences between two strings within the lists. And I don't know where to start from, can someone please help me?

Upvotes: 1

Views: 120

Answers (2)

Brendan Abel
Brendan Abel

Reputation: 37599

itertools can help here.

import itertools


a = ['ATG','TGA','CCC','GCT','TGA']
b = ['TCG','TGA','CCG','GCA','TGA']

for a_word, b_word in itertools.izip(a, b):
    output = ''
    for a_char, b_char in itertools.izip(a_word, b_word ):
        if a_char == b_char:
            output += '*'
        else:
            output += b_char
    print a_word, b_word, output 

Upvotes: 0

Bhargav Rao
Bhargav Rao

Reputation: 52191

You can use zip to combine the two lists and then iterate over them as a pair

Here the tmp variable uses a generator expression within a join to check if the values are different. If they are not, then it will insert a *

>>> for i,j in zip(a,b):
...     tmp = ''.join(v if v!=i[k] else '*' for k,v in enumerate(j) )
...     if tmp!='***':
...           print i,j,tmp
... 
ATG TCG TC*
CCC CCG **G
GCT GCA **A

Upvotes: 2

Related Questions