2024-04-29 15:24:04 发布
网友
给出一个列表:
lists = [[5, 8, 2, "Banana"][3, 6, 9, "Apple"][7, 9, 1, "Cherry"]]
1)如何打印按字母顺序排列的列表,并且只打印列表中的第二个数字?你知道吗
期望输出:
[6, "Apple"][8, "Banana"][9, "Cherry"]
2)按从高到低的第三个数字打印排序后的列表
[3, 6, 9, "Apple"] [5, 8, 2, "Banana"][7, 9, 1, "Cherry"]
>>> sorted([[i[1], i[-1]] for i in lists], key=lambda x:x[1]) [[6, 'Apple'], [8, 'Banana'], [9, 'Cherry']]
这里是:每个子列表都应该有逗号
l = [[5, 8, 2, "Banana"],[3, 6, 9, "Apple"],[7, 9, 1, "Cherry"]] [ x[1::2]for x in sorted(l,key=lambda x : x[2]) ]
输出:
[[9, 'Cherry'], [8, 'Banana'], [6, 'Apple']]
然后使用key=reverse排序
key=reverse
就像这个:
sorted([ x[1::2] for x in sorted(l,key=lambda x : x[2]) ],key=lambda x:x[-1])
[[6, 'Apple'], [8, 'Banana'], [9, 'Cherry']]
既然你只需要代码听起来像
from operator import itemgetter sorted(map(itemgetter(1,-1),lists),key=itemgetter(-1))
这里有一些代码,应该做你想要的。。。老师可能需要一个解释,但是。。。只是警告而已
这里是:每个子列表都应该有逗号
输出:
然后使用
key=reverse
排序就像这个:
输出:
既然你只需要代码听起来像
这里有一些代码,应该做你想要的。。。老师可能需要一个解释,但是。。。只是警告而已
相关问题 更多 >
编程相关推荐