How to replace item in lists in a list in Python

Viewed 359

Now i just want to replace the min, max value with the x in the table.... and i dont know how to ...

for i in table[1:]:
    mn = min(i) if min(i) < mn else mn 
    mx = max(i) if max(i) > mx else mx
    x = (mn+mx)/2
2 Answers

The following should work:

def remove_outliers(table):
    mx = max(map(max, table))
    mn = min(map(min, table))
    avg = (mx + mn) / 2

    for row in table:
        row[:] = [avg if x in (mx, mn) else x for x in row]
    # OR
    for row in table:
        for i, x in enumerate(row):
            if x in (mx, mn):
                row[i] = avg

max(map(max, table)): applies the max function to each row in table, and takes the max of all those "maxes".

row[:] = ...: slice-assignment. This is a mutation on the row object. Simply row = ... would just rebind the loop variable without affecting the list object that is still indexed by table.

[avg if x in (mx, mn) else x for x in row]: general conditional list comprehension. Fairly self-explanatory.

Related