Search code examples
pythonpython-3.xstringlistsubtraction

How to subtract consecutive strings with respect to another string?


I have a list of strings as follows

['ENST00000641515.2', 'ENSG00000186092.6', 'OTTHUMG00000001094.4', 
'OTTHUMT00000003223.4', 'OR4F5', '202', 'OR4F5', '2618', 'UTR5', '1', '60', 
'CDS', '61', '1041', 'UTR3', '1042', '2618', '', 'ENST00000335137.4', 
'ENSG00000186092.6', 'OTTHUMG00000001094.4', '', '', 'OR4F5', '201', 'OR4F5',
 '1054', 'UTR5', '1', '36']

I want to iterate through this list, and if string is 'UTR5', i want to subtract the two consecutive strings after that from each other(latter from the previous). The subtracting values should get added and finally print out the answer.

Example: after first 'UTR5' there is 1 and 60. So i want to subtract 60 - 1. in second 'UTR5' it is 36-1. Final answer should get printed as 94

I'm new to python, can somebody suggest me a script. Thanks in advance. Original list is huge. I have given a shorter version.


Solution

  • lst = ['ENST00000641515.2', 'ENSG00000186092.6', 'OTTHUMG00000001094.4',
           'OTTHUMT00000003223.4', 'OR4F5', '202', 'OR4F5', '2618', 'UTR5', '1', '60',
           'CDS', '61', '1041', 'UTR3', '1042', '2618', '', 'ENST00000335137.4',
           'ENSG00000186092.6', 'OTTHUMG00000001094.4', '', '', 'OR4F5', '201', 'OR4F5',
           '1054', 'UTR5', '1', '36']
    
    total = 0
    for i, x in enumerate(lst):
        if lst[i] == 'UTR5':
            total += (int(lst[i + 2]) - int(lst[i + 1]))
    
    print(total)
    

    take a look at enumerate usage in for loops over iterables.

    Note that it is assumed that the indexes i+1 and i+2 are integers..