Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the differences in all possible ways of list elements

Tags:

python

list

I have list of ascending numbers in a column:

 45
 59 
 68 
 79 
 89
 99

I want the differences between each number in following pattern.

Difference between first consecutive:
    59 - 45
    68 - 59
    79 - 68
    89 - 79
    99 - 89

Difference between second consecutive:
    68 - 45
    79 - 59
    89 - 68
    99 - 79

Difference between third consecutive:
    79 - 45

And so on...

I tried

 with open("file.xls", 'r', newline='') as report: 
     reader = csv.reader(report, delimiter='\t' )                                             
     for row in reader:                                                                       
         list5 = []                                                                           
         if row[0] == "chr5":                                                                 
             list5.append(row[1])                                                             

After appending all the values in the list I tried to find the difference but only for first consecutive elements

v = [list5[i+1]-list5[i] for i in range(len(list5)-1)]  

I am expecting all the output values in a single list.

like image 480
kashiff007 Avatar asked Nov 22 '25 14:11

kashiff007


2 Answers

This sounds like a perfect opportunity for zip.

For example, the following code loops through two separate versions of your list5 list: one for the first (N-1) elements, and one for the 2nd through Nth element:

result = []
for element_i, element_j in zip(list5[1:], list5[:-1]):
   result.append(element_i - element_j)

You can get the same in a list comprehension:

result = [(element_i - element_j) for element_i, element_j in zip(list5[1:], list5[:-1])]
like image 76
acdr Avatar answered Nov 24 '25 04:11

acdr


you can use two for one for calculate difference and one for increase the value of distance between them like this:

[[list5[i+j]-list5[i] for i in range(len(list5)-j)] for j in range(1, len(list5))]
# [[14, 9, 11, 10, 10], [23, 20, 21, 20], [34, 30, 31], [44, 40], [54]]
like image 25
Mojtaba Kamyabi Avatar answered Nov 24 '25 06:11

Mojtaba Kamyabi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!