Search code examples
pythonpython-3.xlistsubtraction

subtracting two values inside a list of list


my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]

Inside the lists, there will be strings as 'chr1', 'chr2', 'chr3'. I want to subtract the values of index 2-1 of each string, and get the total value for 'chr1', 'chr2', 'chr3'

example In the first two strings (65433 - 65419) should get subtract and this should get added to the (65573-65520) because both contains 'chr1'. This should happen for all the lists and final results should be as follows 'chr1' total = x_value, 'chr2' total = y_value, 'chr3' total = x_value

I'm kind of new python.can somebody suggest a code for this.


Solution

  • my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]
    mylist1=list()
    mylist2=list()
    mylist3=list()
    
    for i in my_list:
        if i[0]=='chr1':
            mylist1.append(i[2]-i[1])
        elif i[0]=='chr2':
            mylist2.append(i[2]-i[1])
        elif i[0]=='chr3':
            mylist3.append(i[2]-i[1])
    
    print("chr1:",sum(mylist1))
    print("chr2:",sum(mylist2))
    print("chr3:",sum(mylist3))
    

    sum is already predefined function to use.

    now if you have more chr:

    my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]
    chrset=set()
    for i in my_list:
        chrset.add(i[0])
    
    res = dict.fromkeys(chrset, 0)
    
    for i in my_list:
        res[i[0]]=res[i[0]]+i[2]-i[1]
    print(res)
    

    its lot more easier for one who is new in python, just making a set of chr1,chr2,.... then creating a dictionary and doing operation on it directly.