Skip to content Skip to sidebar Skip to footer

How To Compare Elements In A List Of Lists And Compare Keys In A List Of Lists In Python?

I have the following sequence: seq = [['ATG','ATG','ATG','ATG'],['GAC','GAT','GAA','CCT'],['GCC','GCG','GCA','GCT']] Here is a dictionary key that stores the value of amino acid f

Solution 1:

Here is my stab at the solution.

aminoacid = {'GCC': 'A' ,'TTT' : 'F','TTC' : 'F','TTA' : 'L','TTG' : 'L','CTT' : 'L','CTC' : 'L','CTA' : 'L','CTG' : 'L','ATT' : 'I','ATC' : 'I','ATA' : 'I','ATG' : 'M','GTT' : 'V','GTC' : 'V','GTA' : 'V','GTG' : 'V','TCT' : 'S','TCC' : 'S','TCA' : 'S','TCG' : 'S','CCT' : 'P','CCC' : 'P','CCA' : 'P','CCG' : 'P','ACT' : 'T','ACC' : 'T','ACA' : 'T','ACG' : 'T','GCT' : 'A','GCG' : 'A','GCA' : 'A','GCG' : 'A','TAT' : 'Y','TAC' : 'Y','TAA' : 'STOP','TAG' : 'STOP','CAT' : 'H','CAC' : 'H','CAA' : 'Q','CAG' : 'Q','AAT' : 'N','AAC' : 'N','AAA' : 'K','AAG' : 'K','GAT' : 'D','GAC' : 'D','GAA' : 'E','GAG' : 'E','TGT' : 'C','TGC' : 'C','TGA' : 'STOP','TGG' : 'W','CGT' : 'R','CGC' : 'R','CGA' : 'R','CGG' : 'R','AGT' : 'S','AGC' : 'S','AGA' : 'R','AGC' : 'R','CGT' : 'G','GGC' : 'G','GGA' : 'G','GGG' : 'G',}

seq = [['ATG','ATG','ATG','ATG'],['GAC','GAT','GAA','CCT'],['GCC','GCG','GCA','GCT']]

Psyn = 0;
PNonsyn = 0;
output = [];

#loop through each list in your list of list
for sublist in seq:
    acids = [aminoacid[base] for base in sublist]
    if len(set(acids)) != 1: #if there are different amino acids, then nonsync
        output.append('nonsync')
        PNonsyn += 1
    else: #if same amino acid
        if len(set(sublist)) == 1: #if same base
            output.append(sublist[0]);
        else: #if not same base
            output.append(acids[0]);
            Psyn += 1

print "Psyn = "+ str(Psyn)
print "PNonsyn = "+ str(PNonsyn)
print output

Admittedly it's not a modification of your code, but there is a neat trick here to void the double for loop. Given a list mylist, you could find all uniques elements in a list by calling set(mylist). E.g.

>>> a = ['AGT','AGT','ACG']
>>> set(a)
set(['AGT', 'ACG'])
>>> len(set(a))
2

Post a Comment for "How To Compare Elements In A List Of Lists And Compare Keys In A List Of Lists In Python?"