Python实践Python 运维Python语言与信息数据获取和机器学习

Python开发相关

2017-02-05  本文已影响316人  CoderMiner

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. 检查一个对象占用的内存大小

import sys
x=1
print(sys.getsizeof(x))

#-> 24

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

#-> 28
上一篇下一篇

猜你喜欢

热点阅读