Python开发相关

Python开发中一些实用的开发建议和技巧(试用新人开发者)

Tips#1. 原地交换两个数字

Python提供了一种直观的方式在一行中进行交换两个变量

x, y = 10, 20
print(x, y)
# 10 20

x, y = y, x
print(x, y)
# 20 10

Tips#2. 比较运算符

n = 10
result = 1 < n < 20
print(result)
# True

result = 1 > n < 9
print(result)
# False

Tips#3. 使用三元运算符

基本语法

[on_true] if [expression] else [on_false]

例子

x = 10 if (y == 9) else 20

对于类的对象同样适用

x = (classA if y == 1 else classB)(param1,param2)
def small(a,b,c):
    return a if a <= b and a <= c else (b if b  <=a and b <= c else c)

print(small(1,0,1))
print(small(1,2,2))
print(small(2,2,3))
print(small(5,4,3))

# 0
# 1
# 2
# 3

在list中也可以适用三元运算符

result = [m ** 2 if m > 10 else m ** 4 for m in range(50)]

print(result)
#  [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

Tips#4. 多行字符串

mulstr = "select * from multi_row \
where row_id < 5"
print(mulstr)
# select * from multi_row where row_id < 5

也可以适用三引号

mulstr = """ select * from multi_row
where row_id < 5 """
print(mulstr)
# select * from multi_row where row_id < 5

也可以使用小括号

mulstr = ("select * from multi_row "
"where row_id < 5 "
"order by age")
print(mulstr)
# select * from multi_row where row_id < 5 order by age

Tips#5. 将list中的元素赋予变量

testList = [1,2,3]
x,y,z = testList

print(x,y,z)
# 1 2 3

Tips#6. 打印导入模块的路径

如果想查看某个模块的绝对路径可以使用这个方法

import os
print(os)
# <module 'os' from 'D:\\Program Files\\python36\\lib\\os.py'>

Tips#7. 调试脚本

import pdb
pdb.set_trace()

使用pdb.set_trace()可以在任何地方设置断点

Tips#8. 设置文件分享

通过Python可以在本机启动一个HTTP Server,在你想分享的目录下执行下面的命令

Python2
python -m SimpleHTTPServer
python3
python -m http.server

然后就可以通过浏览器访问8000端口了

效果图

Tips#9. 运行时检测Python的版本

print("Current Python Version: ",sys.version_info >= (3,5))

Tips#10. 在Python中使用Enums

class Shapes:
    Circle, Square, Triangle, Quaduangle = range(4)

print(Shapes.Circle)
print(Shapes.Square)
print(Shapes.Triangle)
print(Shapes.Quaduangle)
# 0
# 1
# 2
# 3

Tips#11. 在方法中返回多个值

def x():
    return 1,2,3,4
a,b,c,d = x()
print(a,b,c,d)
# 1 2 3 4

Tips#12. 检查一个对象占用的内存大小

  • Python 2.7
import sys
x=1
print(sys.getsizeof(x))

#-> 24
  • Python 3

3
4
5
import sys
x=1
print(sys.getsizeof(x))

#-> 28
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,901评论 25 709
  • 前言 Python的创始人为Guido van Rossum。1989年圣诞节期间,在阿姆斯特丹,Guido为了打...
    依依玖玥阅读 8,938评论 6 37
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,800评论 19 139
  • 这两天在看<妈妈的银行账户>,看的过程中才理解序言中提到的美国人有意思的地方在哪里?这样一个没什么波澜起伏,没什么...
    王五月阅读 3,728评论 0 0
  • 在楼梯上下间的相遇中,她看到了那个男人。 第一眼看上去他不是个讨人厌的家伙! 他穿着休闲的棉衣和运动棉裤,衣衫很随...
    生活故事录阅读 1,657评论 0 0