Reputation: 189
My data is as follows:
mx_ranges1 = [
(848,888),
(806,848),
(764,806),
(722,764),
(680,722),
(638,680),
(596,638),
(554,596),
(512,554),
(470,512),
(428,470),
(386,428),
(344,386),
(302,344),
(260,302),
(218,260),
(176,218),
(134,176),
]
a=((mx_ranges1[0][1]-mx_ranges1[0][0])/2)+(mx_ranges1[0][0])
b=((mx_ranges1[1][1]-mx_ranges1[1][0])/2)+(mx_ranges1[1][0])
c=((mx_ranges1[2][1]-mx_ranges1[2][0])/2)+(mx_ranges1[3][0])
print(a)
print(b)
print(c)`
That way is not really efficient, I know it can somehow be represented in a for
loop, I just don't know how I might do it. Please give me some references since I'm new to python and programming in general. I then have another list with y which also need to take the distance then add it to the first element.
Not sure if it can be placed directly into a single 2D array but just doing the first part should be good enough for me. I can do the rest manually.
Upvotes: 1
Views: 297
Reputation: 88236
You can use a simple list comprehension:
[(j-i)/2 + i for i,j in mx_ranges1]
# [868.0, 827.0, 785.0, 743.0, 701.0, 659.0, 617.0 ...
Which is equivalent to the following for loop:
res = []
for i,j in mx_ranges1:
res.append((j-i)/2 + i)
You also mention using numpy arrays. Note that this would be the most efficient and simple way to do it, as it is a matter of Basic Slicing and Indexing:
a = np.array(mx_ranges1)
(a[:,1] - a[:,0]) /2 + a[:,0]
# array([868., 827., 785., 743., ...
Upvotes: 1
Reputation: 27594
Numpy will be much faster!
import numpy as np
mx_ranges1 = [
(848,888),
(806,848),
(764,806),
(722,764),
(680,722),
(638,680),
(596,638),
(554,596),
(512,554),
(470,512),
(428,470),
(386,428),
(344,386),
(302,344),
(260,302),
(218,260),
(176,218),
(134,176),
]
a = np.array(mx_ranges1)
# the first index accessor : says all rows, the second specifies a column
result = (a[:,1] - a[:,0])/2 + a[:,0]
# result contains one value for each row/tuple in `mx_ranges1`
print(result)
This returns:
[868. 827. 785. 743. 701. 659. 617. 575. 533. 491. 449. 407. 365. 323.
281. 239. 197. 155.]
Which contains one value for each row of your input 2D array. So 868 = 888-848/2 + 848.
Upvotes: 1