Python:在列表中排序和打印列表

2024-04-29 15:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

给出一个列表:

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"]


Tags: apple列表排序字母数字listsbananacherry
3条回答
>>> 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排序

就像这个:

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))

这里有一些代码,应该做你想要的。。。老师可能需要一个解释,但是。。。只是警告而已

相关问题 更多 >