我有一个 Python 列表列表,我想根据两个类别对其进行排序。排序列表的最后一个位置应具有最小的数字,并且第一个元素必须大于 400。我想从列表中返回前 3 个。
x_list = [['422', '324', '733443'], ['342', '654', '674335'],
['953', '456', '828854'], ['345', '886', '446678'],
['3224', '533', '654333'], ['7545', '5567', '369990']]
它应该像这样返回:
result = [['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443']]
我试过使用下面的代码,但是无法结合这两个条件来对列表进行排序:
result= []
result += sorted(x_list, key=lambda x: int(x[-1]))[:3]
谁能帮我解决这个问题?非常感谢!!
最佳答案
考虑这段代码:
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”子列表吗?
https://stackoverflow.com/questions/72450566/