首页 > 编程语言 >Python - operator module

Python - operator module

时间:2024-07-31 20:18:13浏览次数:11  
标签:function Sam Python self module marks operator itemgetter

>>> list(map(lambda x, y: x * y, [1,2,3,4], [5,6,7,8]))

[5, 12, 21, 32]

Here we have called the map function and sent a lambda expression as first argument. Instead of the lambda function, you can send operator.mul.

>>> list(map(operator.mul, [1,2,3,4], [5,6,7,8]))

[5, 12, 21, 32]

The operator module has two more useful functions that we can use instead of lambda functions while doing functional programming. These are itemgetter and attrgetter functions. The itemgetter function can be used to get items from sequences and attrgetter can be used to extract attributes from objects. Let us see how to use these functions:

>>> from operator import itemgetter

>>> employees = [ ('Rajendra', 'Kumar', 32, 6000),

...  ('Sam', 'Saxena', 43, 8000),

... ('Shyamchandra', 'Verma', 23, 3000),

... ('Sam', 'Gupta', 33, 7000),

... ('Sam', 'Sung', 31, 5000)

... ]

We imported the itemgetter function from the operator module. We have a list of tuples, which we used earlier when learning about sorted function. To sort this list of tuples based on element at the second index, we would write this:

>>> sorted(employees, key=lambda t: t[2])

[('Shyamchandra', 'Verma', 23, 3000), ('Sam', 'Sung', 31, 5000), ('Rajendra', 'Kumar', 32, 6000), ('Sam', 'Gupta', 33, 7000), ('Sam', 'Saxena', 43, 8000)]

Instead of the lambda function, we can use the itemgetter function which is more readable and faster and gives us the same result.

>>> sorted(employees, key=itemgetter(2))

[('Shyamchandra', 'Verma', 23, 3000), ('Sam', 'Sung', 31, 5000), ('Rajendra', 'Kumar', 32, 6000), ('Sam', 'Gupta', 33, 7000), ('Sam', 'Saxena', 43, 8000)]

We can do multiple levels of sorting by sending more than one index values to the itemgetter function.

>>> sorted(employees, key=itemgetter (1,2))

[('Sam', 'Gupta', 33, 7000), ('Rajendra', 'Kumar', 32, 6000), ('Sam', 'Saxena', 43, 8000), ('Sam', 'Sung', 31, 5000), ('Shyamchandra', 'Verma', 23, 3000)]

The sorting is done first by index 1 element and then by index 2 element.

The next example shows how to use the attrgetter function.

from operator import attrgetter


class Student:
    def __init__(self, name, marks, birthYear):
        self.name = name  
        self.marks = marks
        self.birthYear = birthYear

    def __str__(self):
        return f'{self.name} {self.marks} {self.birthYear}'


s1 = Student('John', 97, 1988)
s2 = Student('Sam', 89, 1987)
s3 = Student('Pam', 99, 1982)
s4 = Student('Pam', 99, 1978)
L = [s1, s2, s3, s4]
L.sort(key=attrgetter('marks')) 

for i in L:
    print(i)

print()
L.sort(key=attrgetter('marks', 'birthYear')) 

for i in L:
    print(i)

Output-

Sam 89 1987

John 97 1988

Pam 99 1982

Pam 99 1978

Sam 89 1987

John 97 1988

Pam 99 1978

Pam 99 1982

For the key parameter of the sort method, we have called the attrgetter function with the marks attribute. So, the list will be sorted based on the marks attribute. We can have multiple levels of sorting; in the next call we have sent two strings, so first it will sort by marks and then by birthYear.

 

标签:function,Sam,Python,self,module,marks,operator,itemgetter
From: https://www.cnblogs.com/zhangzhihui/p/18335380

相关文章

  • Python操作excel常用操作介绍,入门首选
            使用Python操作Excel文件有许多常用操作。以下是一些常见的操作及其简要描述,下面是全面详细的示例,展示如何使用Python操作Excel文件,我们将使用pandas和openpyxl库来进行各种操作。常用库pandas:用于数据分析和处理,支持读取和写入Excel文件。openpyxl:用于读......
  • Python蒙特卡罗(Monte Carlo)模拟计算投资组合的风险价值(VaR)
    原文链接:http://tecdat.cn/?p=22862原文出处:拓端数据部落公众号如何使用Python通过蒙特卡洛模拟自动计算风险值(VaR)来管理投资组合或股票的金融风险。金融和投资组合风险管理中的VaR?VaR是"风险价值"的缩写,是许多公司和银行用来确定其公司内部金融风险水平的工具。风险值是为......
  • Python 元类深析:定制类创建的高级工
    元类是Python中一个强大而高级的特性,它允许我们自定义类的创建过程。本文将详细介绍Python元类的概念、工作原理以及常见用途。一. 什么是元类简单来说,元类就是用来创建类的类。在Python中,类也是对象,而元类就是用来创建这些类对象的。我们知道类是用来创建对象的......
  • 【视频讲解】Python用LSTM、Wavenet神经网络、LightGBM预测股价
    原文链接:https://tecdat.cn/?p=37184原文出处:拓端数据部落公众号 分析师:YuyanYe在金融科技的浪潮中,量化投资方法以其数据驱动和模型导向的特性,日益成为资本市场分析的重要工具。特别是,长短期记忆网络(LSTM)、Wavenet以及LightGBM等先进的机器学习算法,因其在时间序列预测中的卓......
  • Python写UI自动化--playwright(点击操作)
    本篇介绍playwright点击操作,click()方法的常用参数目录0.selector(必需)1.modifiers(可选)2.position(可选)3.button(可选)4.click_count(可选)5.delay6.timeout(可选)7.force=True(可选)8.trial=True(可选)9.no_wait_after(可选)注意事项0.selecto......
  • 【2024最新版】超详细Python+Pycharm安装保姆级教程,Python+Pycharm环境配置和使用指南
    本文将从Python解释器安装到Pycharm专业版安装和配置汉化等使用都进行了详细介绍,希望能够帮助到大家。Python解释器&Pycharm安装包&Pycharm破姐插件我都打包好了。这份完整版的Python安装包已经上传至CSDN官方,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费获取......
  • python实现jenkins凭据录入
    #新增配置importjenkins.model.*importjenkins.plugins.publish_over_ssh.BapSshHostConfigurationdefinst=Jenkins.getInstance()defpublish_ssh=inst.getDescriptor("jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin")defconfiguration=new......
  • funccache:革命性的Python函数缓存工具,轻松提升代码效率!
    funccacheEnglish|中文如其名,funccache实现函数缓存功能,由GQYLPY团队研发的一个框架,可缓存某个函数或某个类中定义的所有方法的返回值。你的程序中有一个函数会被多次调用,并且返回值不变,你会怎么做?为提高代码效率,你会先调用一次该函数并把返回值存到一个变量,之后就使用......
  • Python - Functional programming
    Functionalprogrammingisaprogrammingparadigminwhichmostoftheworkinaprogramisdoneusingpurefunctions.Apurefunctionisafunctionwithoutanysideeffects;itsreturnvalueisalwaysdeterminedbyitsinputarguments,soitalwaysreturn......
  • Python - Lambda expressions as closures
    Aclosureisanestedfunctionthatcanaccessfreevariablesfromanenclosingfunctionevenafterithasfinisheditsexecution.Weknowthat,likenestedfunctiondefinitions,lambdaexpressionscanreferencevaluesfromtheenclosingscope,solambda......