Python面试必考重点之列表,元组和字典第十关——类的Magic方法/operator模块/sort方法和sorted函数的key参数

257 阅读3分钟

「这是我参与2022首次更文挑战的第10天,活动详情查看:2022首次更文挑战」。

面试题第十关:

第一部分——考点:

  1. 类的Magic方法
  2. operator模块
  3. sort方法和sorted函数的key参数

第二部分——面试题:

1.面试题一:如果列表元素是对象,对这样的列表排序有哪些方法

1.面试题二:如果列表元素是对象,进行倒序排列的方法有哪些


第三部分——解析:

面试题一 之 如果列表元素是对象,对这样的列表排序有哪些方法:

第一种:

class MyClass:
	def __init__(self):
		self.value = 0
	def __lt__(self,other):
		return self.value < other.value

my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value = 10

my3 = MyClass()
my3.value = 30

a = [mya,my2,my3]		
print(a)     #这是要排序的a就是一个对象

a.sort()

print(a[0].value)   # 输出为:10
print(a[1].value)	#		 20
print(a[2].value)	#		 30

第二种:

class MyClass:
	def __init__(self):
		self.value = 0

	def __gt__(self,other):
		return self.value > other.value

my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value = 10

my3 = MyClass()
my3.value = 30

a = [mya,my2,my3]		
print(a)     #这是要排序的a就是一个对象

a.sort()

print(a[0].value)   # 输出为:10
print(a[1].value)	#		 20
print(a[2].value)	#		 30

第三种:

class MyClass:
	def __init__(self):
		self.value = 0

my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value = 10

my3 = MyClass()
my3.value = 30

a = [mya,my2,my3]		
print(a)     #这是要排序的a就是一个对象

import operator

a.sort(key = operator.attrgetter('value'))

print(a[0].value)   # 输出为:10
print(a[1].value)	#		 20
print(a[2].value)	#		 30

面试题二 之 如果列表元素是对象,进行倒序排列的方法有哪些:

前两种方法:

把上面两种魔术方法的大于号小于号颠倒

第三种方法:

class MyClass:
	def __init__(self):
		self.value = 0

my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value = 10

my3 = MyClass()
my3.value = 30

a = [mya,my2,my3]		
print(a)     #这是要排序的a就是一个对象

import operator

a.sort(key = operator.attrgetter('value'),reverse = True)

print(a[0].value) 
print(a[1].value)
print(a[2].value)

总结:

  • 为类添加__gt__和__lt__方法,可以让该类的实例支持sort方法和sorted函数;

  • 通过改变__gt__和__lt__方法的返回值,或者设置sort方法和sorted函数的reverse参数,可以让列表倒序排列。

  • 需要注意的是:我们上面使用的就是Python类中的magic方法,我们通过复写这些方法,实现了我们需要的特殊的功能!

  • operator模块输出一系列对应Python内部操作符的函数。我们上面使用的就是其中的函数哦~

  • 关于sort方法和sorted函数,前面有道题用到过,当时也很详细的讲解过,本道题就是带我们熟悉一下key参数~

🔆In The End!

👑有关于Me

个人简介:我是一个硬件出身的计算机爱好者,喜欢program,源于热爱,乐于分享技术与所见所闻所感所得。文章涉及Python,C,单片机,HTML/CSS/JavaScript及算法,数据结构等。

从现在做起,坚持下去,一天进步一小点,不久的将来,你会感谢曾经努力的你!

认真仔细看完本文的小伙伴们,可以点赞收藏并评论出你们的读后感。并可关注本博主,在今后的日子里阅读更多技术文哦~

如有错误或者言语不恰当的地方可在评论区指出,谢谢!
如转载此文请联系我征得本人同意,并标注出处及本博主名,谢谢 !