Pythond的几种高级语法糖

一、for - else

 for i in [1, 2, 3, 4]:
    print(i)
 else:
    print("我是一个美丽的意外:%d" % i)

二、可变参数

Python 函数不仅支持默认参数,也支持可变参数,一颗星表示不限数量的单值参数,两颗星表示不限数量的键值对参数。我们还是举例说明吧:设计一个函数,返回多个输入数值的和。我们固然可以把这些输入数值做成一个list传给函数,但这个方法,远没有使用一颗星的可变参数来得优雅:

def multi_params(*args, **kwargs):
    for i in args:
        print(i)
    print({k[0]: k[1] for k in kwargs.items()})


multi_params(1, 2, 3, 4, a=1,b=9)

三、with - as

系统会自动关闭连接句柄,减低内存泄漏的风险:e.g.

with open(self.output_sentence_entity_file, "w", encoding='utf-8') as outfile:
    outfile.write("\n\n")

四、三元表达式

a = ' ' if ('[]' == x or x is np.nan) else x

五、列表推导式

a = [i for i in [1,2,3,4] if i%2==0]

六、lambda函数

print((lambda x, y: x * y)(10, 3))

七、yield 以及生成器和迭代器

def get_multi(n):
    for i in range(n):
        yield(pow(i, 3))
for i in get_multi(4):
    print(i, end=';')
print([i for i in get_multi(4)])

八、断言assert

i=[]
assert type(i) is list
assert type(i) is str
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AssertionError
assert isinstance(i, (int, list))
assert isinstance(i, (int, str))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AssertionError

九、装饰器

在每个函数运行的时候要显示当前函数的运行时长,装饰器如何做到简单、优雅。下面的例子,很好地展示了这一点

def timer(func):
    import time
    def wrapper(*args, **kwargs):
        t0 = time.time()
        func(*args, **kwargs)
        t1 = time.time()
        print('%s, time elapsed %.2fs' % (func.__name__, t1 - t0))
    return wrapper

@timer
def build():
    import time
    time.sleep(10)

build()

十、列表索引

l = ['Google', 'Facebook', 'Ins', 'Meta', 'Netflix', 'Apple', 'Microsoft']
print(l[0:1])
['Google']
print(l[:-1])
['Google', 'Facebook', 'Ins', 'Meta', 'Netflix', 'Apple']
print(l[0:-1])
['Google', 'Facebook', 'Ins', 'Meta', 'Netflix', 'Apple']
print(l[0::-1])
['Google']
print(l[::-1])
['Microsoft', 'Apple', 'Netflix', 'Meta', 'Ins', 'Facebook', 'Google']
print(l[::-2])
['Microsoft', 'Netflix', 'Ins', 'Google']
print(l[::2])
['Google', 'Ins', 'Netflix', 'Microsoft']
print(l[-1])
Microsoft

十一、zip

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值