python 函数二三事

python 函数二三事

python中的函数是一等公民,非常重要,人称一等函数。今天和大家分享几个函数中有用的二三事。

1. sorted

sorted 是python内置的高阶函数,用于对可迭代的对象进行排序,如列表,字典,元组,集合和字符串, 返回的是一个列表

sorted(iterable, /, *, key=None, reverse=False)

alist = ['bobo', 'annyaa', 'bush']
adict = {1: 'bobo', 4:'annyaa', 2:'bush'}
astr = "pythoncheck"

print(sorted(alist))
print(sorted(adict.items()))
print(sorted(astr))

## sorted 可以指定定制key来排序
print(sorted(alist, key=lambda x: len(x)))
print(sorted(adict.items(), key=lambda x: len(x[1])))
print(sorted(adict.items(), key=lambda x: x[1][1]))

# ['annyaa', 'bobo', 'bush']
# [(1, 'bobo'), (2, 'bush'), (4, 'annyaa')]
# ['c', 'c', 'e', 'h', 'h', 'k', 'n', 'o', 'p', 't', 'y']
# ['bobo', 'bush', 'annyaa']
# [(1, 'bobo'), (2, 'bush'), (4, 'annyaa')]
# [(4, 'annyaa'), (1, 'bobo'), (2, 'bush')]

2. 函数参数* 与**

python函数支持关键参数,也支持非关键参数,对于参数是可变的情况下特别的有用; python 非关键参数支持列表和字典模式。

def afun(parama=1, *paramb, **args):
    print(parama)
    print(paramb)
    print(args)
    
# parama为关键参数,paramb为列表可变参数,args是字典可变参数

print('*' * 10)
afun(parama=1)
print('*' * 10)
afun(1, "e1", "e2", a=1, b=2)

# **********
# 1
# ()
# {}
# **********
# 1
# ('e1', 'e2')
# {'a': 1, 'b': 2}

3. 通过字符串方式调用方法methodcaller

如何使框架设计,相信你一定会用到methodcaller:通过字符串方式调用方法

from operator import methodcaller
class Test:
    def aprint(self, info):
        print('hello, {}'.format(info))


caller = methodcaller("aprint", "aiweker")
t = Test()
caller(t)

# hello, aiweker

从上面可知字符串aprint其实是函数名, 通过methodcaller可以轻松调用函数,可以将函数放在配置文件中来调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值