[英]How to create a lambda function from a tuple of values
The basic objective is to sort a list of lists based on a field in the inner lists. 基本目标是基于内部列表中的字段对列表列表进行排序。 So i have the below Python code for doing it: 所以我有以下Python代码:
import sys
def sort_cleaned_data(data, fields=None):
if not isinstance(fields, tuple):
raise ValueError("Argument to the function has to be a tuple")
else:
if all(list(map(lambda x:isinstance(x, int), fields))):
sorted_data = sorted(data, key=lambda x:(x[2],x[1]))
return sorted_data
else:
raise ValueError("All the values inside the fields tuple have to be integers")
data = [
["John", 34, 2],
["Ashley", 30, 2],
["Peter", 28, 5],
["Bill", 29, 5],
["Jennifer", 65, 4],
["Laura", 33, 3]
]
try:
sorted_data = sort_cleaned_data(data, fields=(2,1))
except ValueError as e:
print(e)
sys.exit(1)
for d in sorted_data:
print(d)
In the function sort_cleaned_data i have the fields tuple which contain the fields of the inner array on which to sort. 在函数sort_cleaned_data中,我有字段元组,其中包含要对其进行排序的内部数组的字段。 So i have to dynamically generate the function : key=lambda x:(x[2],x[1])
based on the fields list. 所以我必须根据字段列表动态生成函数: key=lambda x:(x[2],x[1])
。
I think this is the case of eval in Python but i am not sure how to do this . 我认为这是Python中的eval的情况,但我不知道如何做到这一点。 Can someone please help me here . 有人可以帮我这里。
Many thanks in advance. 提前谢谢了。
Using a comprehension: 使用理解:
sorted(data, key=lambda x: tuple(x[i] for i in fields))
Now fields
can be arbitrary in size and values, provided x
(inner list) has enough elements to not raise IndexError. 现在fields
大小和值可以是任意的,只要x
(内部列表)具有足够的元素就不会引发IndexError。
This is overly complicated. 这太复杂了。 Just use operator.itemgetter
to create your key function. 只需使用operator.itemgetter
即可创建关键功能。
import operator
def sort_cleaned_data(data, fields=None):
return sorted(data, key=operator.itemgetter(*fields))
data = [
["John", 34, 2],
["Ashley", 30, 2],
["Peter", 28, 5],
["Bill", 29, 5],
["Jennifer", 65, 4],
["Laura", 33, 3]
]
sorted_data = sort_cleaned_data(data, fields=(2,1))
for d in sorted_data:
print(d)
Output: 输出:
['Ashley', 30, 2]
['John', 34, 2]
['Laura', 33, 3]
['Jennifer', 65, 4]
['Peter', 28, 5]
['Bill', 29, 5]
You're making it much more complicated than it has to be: 你使它变得比以前复杂得多:
def sort_cleaned_data(data, fields):
return sorted(data, key=lambda x: (x[fields[0]], x[fields[1]]))
data = [
["John", 34, 2],
["Ashley", 30, 2],
["Peter", 28, 5],
["Bill", 29, 5],
["Jennifer", 65, 4],
["Laura", 33, 3]
]
sorted_data = sort_cleaned_data(data, fields=(2,1))
for d in sorted_data:
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.