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.
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])]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With