简体   繁体   中英

Switching between min and max by user inter action

I have the following code which allows the user to choose between min and max filtering. However, min works on element 1 but max works on element 2 . Is there a better way to implement it?

from operator import itemgetter

data = [['A', '2', '4'], ['B', '2', '12'],
        ['C', '3', '88'], ['D', '4', '88']]
 
fn_max = False

if fn_max is True:
    mx = max(data, key=itemgetter(2))[2]
    mx_values = [d for d in data if d[2] == mx]
else:
    mx = min(data, key=itemgetter(1))[1]
    mx_values = [d for d in data if d[1] == mx]   
    
print(mx_values)

You can put them into a function:

from operator import itemgetter

data = [['A', '2', '4'], ['B', '2', '12'],
        ['C', '3', '88'], ['D', '4', '88']]


def my_func(fn_max):
    func, i = (max, 2) if fn_max else (min, 1)
    mx = func(data, key=itemgetter(i))[i]
    return [d for d in data if d[i] == mx]


fn_max = False
print(my_func(fn_max))

Output:

[['A', '2', '4'], ['B', '2', '12']]

This is arguably better (although it's unclear what you need it for, so it's hard to say if it would really be better):

data = [
    ['A', 2, 4], 
    ['B', 2, 12],
    ['C', 3, 88], 
    ['D', 4, 88]
]

def fn_filter(fn, column, data):
    value = fn(rec[column] for rec in data)
    return list(filter(lambda rec: rec[column] == value, data))


print(fn_filter(min, 1, data))
print(fn_filter(max, 2, data))

Result:

[['A', 2, 4], ['B', 2, 12]]
[['C', 3, 88], ['D', 4, 88]]

fn_filter allows you to apply any function fn to a specific column column of the dataset data and will return a list of all the records in data that have that same value in that same column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM