[英]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.我有以下代码,允许用户在
min
和max
过滤之间进行选择。 However, min
works on element 1
but max
works on element 2
.但是,
min
适用于元素1
但max
适用于元素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:您可以将它们放入 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: 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. fn_filter
允许您将任何 function fn
应用于数据集data
的特定列column
,并将返回data
中在同一列中具有相同值的所有记录的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.