如何使用两个条件对 Python 中的列表进行排序?

How to sort a list in Python using two conditions?

我在 Python 中有一个列表列表,我想根据两个类别对其进行排序。排序后的列表在最后一个位置应该有最小的数字,而且第一个元素必须大于 400。我想 return 列表中的前 3 个。

x_list = [['422', '324', '733443'], ['342', '654', '674335'], 
         ['953', '456', '828854'], ['345', '886', '446678'], 
         ['3224', '533', '654333'], ['7545', '5567', '369990']]

它应该return像这样:

result = [['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443']]

我试过使用下面的代码,但无法结合这两个条件对列表进行排序:

result= []
result += sorted(x_list, key=lambda x: int(x[-1]))[:3]

谁能帮我解决这个问题?非常感谢!!

我会先过滤列表只保留第一个元素大于400的值,然后排序最终结果基于最后一个元素的升序,正如您最初拥有的那样。例如:

x_list = [['422', '324', '733443'], ['342', '654', '674335'],
         ['953', '456', '828854'], ['345', '886', '446678'],
         ['3224', '533', '654333'], ['7545', '5567', '369990']]

x_list2 = [x for x in x_list if int(x[0]) > 400]
x_list2.sort(key=lambda x: int(x[2]))
x_list2 = x_list2[:3]

print(x_list2)
# [['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443']]

或者您也可以一步进行排序和过滤:

x_list = [['422', '324', '733443'], ['342', '654', '674335'],
         ['953', '456', '828854'], ['345', '886', '446678'],
         ['3224', '533', '654333'], ['7545', '5567', '369990']]

x_list2 = sorted((x for x in x_list if int(x[0]) > 400), key=lambda x: int(x[2]))[:3]

print(x_list2)
# [['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443']]
x_list = [['422', '324', '733443'], ['342', '654', '674335'],
         ['953', '456', '828854'], ['345', '886', '446678'],
         ['3224', '533', '654333'], ['7545', '5567', '369990']]

x_list = [a for a in x_list if float(a[0]) > 400]  # Filters out values <= 400
x_list.sort(key=lambda x : x[2])  # Sorts by the last element
x_list = x_list[:3]  # Only keeps the first 3 values
print(x_list)

考虑这段代码:

filter_first = [el for el in x_list if int(el[0]) > 400]
sorted(filter_first, key=lambda el: el[-1])

这给了我

[['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443'], ['953', '456', '828854']]

这与您声称的输出结果不同,但我认为它满足您声明的所有要求。你能解释一下“953”子列表吗?

这是一个可自定义的函数:

def sort_filtered(list_, key=lambda x: x[2], filter_=lambda x: x[0] > 400, n=3):   
    # Turn values into floats so we can sort them
    float_list = [[float(x) for x in y] for y in list_]
    return [x for x in sorted(float_list, key=key) if filter_][:n]