Search code examples
pythonlistdivisiondivide

How to divide several lists together while maintaining order?


I am trying to create a three list (one contain average values for blue change, another for the green channel, and the last one for the red channel). However, I am having trouble dividing these three list together.

Here is a small example of what I am trying to achieve

a = [4,2,2,3]
b = [4,2,1,4]
c = [3,2,1,2]
result = [(4/4/3), (2/2/2), (2/1/1), (3/4/2)]

But here is the code:

c_1 = [img2[92, 72]]
c_2 = [img2[260,76]]
c_3 = [img2[422,79]]
c_All = [img2[92, 72],img2[260,76],img2[422,79]]

bAvgWells = []
gAvgWells = []
rAvgWells = [] 

for center in c_All:
    b = img2[center[0]-22: center[0]+22, center[1]-26: center[1]+26, 0]
    g = img2[center[0]-22: center[0]+22, center[1]-26: center[1]+26, 1]
    r = img2[center[0]-22: center[0]+22, center[1]-26: center[1]+26, 2]
    bAvg = np.mean(b)
    gAvg = np.mean(g)
    rAvg = np.mean(r)
    #Add each value from loop into list in line 54-56
    bAvgWells.append(bAvg)
    gAvgWells.append(gAvg)
    rAvgWells.append(rAvg)

avg_one = []
color_avg = []
end_b = len(bAvgWells)
end_f = len(avg_one)
#Divdes the list together for averages of all columns
for i in range(end_b):
    a = (bAvgWells[i]/gAvgWells[i])
    avg_one.append(a)
for k in range(end_f):
    b = (a[i]/rAvgWells[i])
    color_avg.append(b)
print (color_avg)

Error: "Mean of empty slice"


Solution

  • This begs for a functional approach:

    >>> from functools import reduce, partial
    >>> import operator
    >>> a = [4,2,2,3]
    >>> b = [4,2,1,4]
    >>> c = [3,2,1,2]
    >>> list(map(partial(reduce, operator.truediv), zip(a, b, c)))
    [0.3333333333333333, 0.5, 2.0, 0.375]
    

    Or expressing the same thing using a list comprehension:

    >>> [reduce(operator.truediv, z) for z in zip(a, b, c)]