Mean from a list with a condition in Python

Viewed 64
list = [[159.2213, 222.2223, 101.2122]
        [359.2222, 22.2210, 301.2144]]

if list[1][0] < list[0][0]:
    avg = (list[1][0] + list[0][0] - 200)/2
else:
    avg = (list[1][0] + list[0][0] + 200)/2

Hello! I want to do this for every column and output the results in another list.

4 Answers

Fix

You may loop iterate the number of cols there is

values = [[159.2213, 222.2223, 101.2122], [359.2222, 22.2210, 301.2144]]
avgs = []
for idx_col in range(len(values[0])):
    if values[1][idx_col] < values[0][idx_col]:
        avg = (values[1][idx_col] + values[0][idx_col] - 200) / 2
    else:
        avg = (values[1][idx_col] + values[0][idx_col] + 200) / 2
    avgs.append(avg)

Simplify

You can use zip to iterate on both rows at a time, and simplify the if/else condition

avgs = []
for first_row, second_row in zip(*values):
    factor = -1 if second_row < first_row else 1
    avgs.append((first_row + second_row + (200 * factor)) / 2)

Best with numpy

Easy syntax and best performance

import numpy as np

values = np.array(values)
res = values.sum(axis=0) / 2
res += np.where(values[1] < values[0], -100, 100)

A list comprehension would look like this:

avg = [(x + y + (200 if x <= y else -200)) / 2 for x, y in zip(*lst)]

Arguably easier if you use numpy:

arr = np.array(lst)
avg = 0.5 * (arr.sum(axis=0) + np.copysign(200, np.diff(arr, axis=0)))
lis = [[159.2213, 222.2223, 101.2122],
        [359.2222, 22.2210, 301.2144]]
res = []
for i in range(len(lis[0])):
    if lis[1][i] < lis[0][i]:
        res.append((lis[1][i] + lis[0][i] - 200)/2)
    else:
        res.append((lis[1][i] + lis[0][i] + 200)/2)

This should work, however using numpy would be a better solution for these kind of problems.

You can do it like this:

list = [[159.2213, 222.2223, 101.2122]
        [359.2222, 22.2210, 301.2144]]

results = []

for x,y in zip(list[0],list[1]):
    if y < x:
        avg = (y + x - 200)/2
    else:
        avg = (y + x + 200)/2  
    results.append(avg)  
Related