栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python常用语法糖

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python常用语法糖

变量交换
# Unrecommended
temp = a
a = b
b = temp

# Recommended
a, b = b, a

链式比较
# Unrecommended
if grade > 60 and grade < 90:
    print("passed")

# Recommended
if 60 < grade < 90:
    print("passed")

三目运算
Python 不支持三目运算符 ? :
# Unrecommended
if torch.cuda.is_available():
    device = torch.device("cuda")
else:
    device = torch.device("cpu")

# Recommended
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

文件操作
# Unrecommended
f = open('file.txt', 'w')
f.write("test")
f.close()
    
# Recommended
with open('file.txt', 'w') as f:
    f.write('test')

字符串拼接
# Unrecommended
list = ['1','2','3','4','5']
str = ""
for item in list:
    str += item

# Recommended
str = ''.join(list)

列表推导
生成列表
# Unrecommended
list = []
for i in range(5):
    list.append(i)
    
# Recommended: List Comprehension
list = [i for i in range(5)]
过滤列表元素
# Unrecommended
odd = []
for i in list:
    if i % 2 != 0:
        odd.append(i)

# Recommended
odd = [i for i in list if i % 2 != 0]
# or
odd = filter(lambda x: x % 2 != 0, list)

内置函数 map
Python 2.x 直接返回列表
>>> def square(x) :            
...     return x ** 2

>>> map(square, [1, 2, 3, 4, 5])   
[1, 4, 9, 16, 25]

>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  
[1, 4, 9, 16, 25]
Python 3.x 返回迭代器,使用 list() 转换为列表
>>> def square(x):         
...     return x ** 2

>>> map(square, [1, 2, 3, 4, 5])    
     	

>>> list(map(square, [1, 2, 3, 4, 5]))
[1, 4, 9, 16, 25]

>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))   
[1, 4, 9, 16, 25]

装饰器
def funA(fun):
    print("this is A")
    fun()
    return "this is result"

@funA
def funB():
    print("this is B")

if __name__ == "__main__":
    print(funB)
# this is A
# this is B
# this is result    

最后祝大家天天进步!!学习Python最重要的就是心态。我们在学习过程中必然会遇到很多难题,可能自己想破脑袋都无法解决。这都是正常的,千万别急着否定自己,怀疑自己。如果大家在刚开始学习中遇到困难,想找一个python学习交流环境,可以 加入我们,领取学习资料、一起讨论。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/738912.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号