从公众号上看到了一篇文章《30个python编程技巧!》,觉得有些挺有用的,有的也一直在用,就挨个实现了一下。

1、原地交换两个数字

In [1]:
x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)

10 20
20 10

2、链状比较操作符

In [3]:
n = 10
print(1 < n < 20)
print(1 > n <= 9)

True
False

3、使用三元操作符来实现条件赋值

[表达式为真的返回值] if [表达式] else [表达式为假的返回值]

In [4]:
y = 20
x = 9 if (y == 10) else 8
print(x)

8

In [6]:
# 找abc中最小的数
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
3
3

In [7]:
# 列表推导
x = [m**2 if m>10 else m**4 for m in range(50)]
print(x)

[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]

4、多行字符串

In [15]:
multistr = "select * from multi_row \
where row_id < 5"
print(multistr)

select * from multi_row where row_id < 5

In [16]:
multistr = """select * from multi_row
where row_id < 5"""
print(multistr)

select * from multi_row
where row_id < 5

In [17]:
multistr = ("select * from multi_row"
"where row_id < 5"
"order by age")
print(multistr)

select * from multi_rowwhere row_id < 5order by age

5、存储列表元素到新的变量

In [18]:
testList = [1, 2, 3]
x, y, z = testList    # 变量个数应该和列表长度严格一致
print(x, y, z)

1 2 3

6、打印引入模块的绝对路径

In [19]:
import threading
import socket
print(threading)
print(socket)

<module 'threading' from 'd:\\python351\\lib\\threading.py'>
<module 'socket' from 'd:\\python351\\lib\\socket.py'>

7、交互环境下的“_”操作符

在python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”

8、字典/集合推导

In [1]:
testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

9、调试脚本

用pdb模块设置断点

In [ ]:
import pdb
pdb.ste_trace()

10、开启文件分享

python允许开启一个HTTP服务器从根目录共享文件

In [ ]:
python -m http.server

11、检查python中的对象

In [3]:
test = [1, 3, 5, 7]
print(dir(test))

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

In [4]:
test = range(10)
print(dir(test))

['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']

12、简化if语句

In [ ]:
# use following way to verify multi values
if m in [1, 2, 3, 4]:
# do not use following way
if m==1 or m==2 or m==3 or m==4:

13、运行时检测python版本

In [12]:
import sys
if not hasattr(sys, "hexversion") or sys.version_info != (2, 7):print("sorry, you are not running on python 2.7")print("current python version:", sys.version)

sorry, you are not running on python 2.7
current python version: 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]

14、组合多个字符串

In [19]:
test = ["I", "Like", "Python"]
print(test)
print("".join(test))

['I', 'Like', 'Python']
ILikePython

15、四种翻转字符串、列表的方式

In [21]:
# 翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)

[5, 3, 1]

In [23]:
# 在一个循环中翻转并迭代输出
for element in reversed([1, 3, 5]):print(element)

5
3
1

In [24]:
# 翻转字符串
print("Test Python"[::-1])

nohtyP tseT

In [25]:
# 用切片翻转列表
print([1, 3, 5][::-1])

[5, 3, 1]

16、用枚举在循环中找到索引

In [26]:
test = [10, 20, 30]
for i, value in enumerate(test):print(i, ':', value)

0 : 10
1 : 20
2 : 30

17、定义枚举量

In [27]:
class shapes:circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)

0
1
2
3

18、从方法中返回多个值

In [28]:
def x():return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)

1 2 3 4

19、使用*运算符unpack函数参数

In [35]:
def test(x, y, z):print(x, y, z)
testDic = {'x':1, 'y':2, 'z':3}
testList = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)

z x y
1 2 3
10 20 30

20、用字典来存储表达式

In [37]:
stdcalc = {"sum": lambda x, y: x + y,"subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))

12
6

21、计算任何数的阶乘

In [38]:
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)

6

22、找到列表中出现次数最多的数

In [40]:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))

4

23、重置递归限制

python限制递归次数到1000,可以用下面方法重置

In [41]:
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())

1000
1200

24、检查一个对象的内存使用

In [42]:
import sys
x = 1
print(sys.getsizeof(x))    # python3.5中一个32比特的整数占用28字节

28

25、使用slots减少内存开支

In [47]:
import sys
# 原始类
class FileSystem(object):def __init__(self, files, folders, devices):self.files = filesself.folder = foldersself.devices = devices
print(sys.getsizeof(FileSystem))
# 减少内存后
class FileSystem(object):__slots__ = ['files', 'folders', 'devices']def __init__(self, files, folders, devices):self.files = filesself.folder = foldersself.devices = devices
print(sys.getsizeof(FileSystem))

1016
888

26、用lambda 来模仿输出方法

In [49]:
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)

python tips 1000 1001

27、从两个相关序列构建一个字典

In [50]:
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))

{1: 10, 2: 20, 3: 30}

28、搜索字符串的多个前后缀

In [52]:
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))

True
True

29、不使用循环构造一个列表

In [55]:
import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))

[-1, -2, 30, 40, 25, 35]

30、实现switch-case语句

In [58]:
def xswitch(x):return  xswitch._system_dict.get(x, None)
xswitch._system_dict = {"files":10, "folders":5, "devices":2}
print(xswitch("default"))
print(xswitch("devices"))

None
2

python的30个编程技巧相关推荐

  1. python3实用编程技巧_适合Python初学者的一些编程技巧

    这篇文章主要介绍了给Python初学者的一些编程技巧,皆是基于基础的一些编程习惯建议,需要的朋友可以参考下 交换变量 x = 6 y = 5 x, y = y, x print x >>& ...

  2. 编程软件python中的if用法-适合Python初学者的一些编程技巧

    这篇文章主要介绍了给Python初学者的一些编程技巧,皆是基于基础的一些编程习惯建议,需要的朋友可以参考下 交换变量 x = 6 y = 5 x, y = y, x print x >>& ...

  3. 给Python初学者的一些编程技巧

    这篇文章主要介绍了给Python初学者的一些编程技巧,皆是基于基础的一些编程习惯建议,需要的朋友可以参考下 交换变量 x = 6 y = 5x, y = y, xprint x >>> ...

  4. 【笔记】效率之门——Python中的函数式编程技巧

    文章目录 Python函数式编程 1. 数据 2. 推导式 3. 函数式编程 3.1. Lambda函数 3.2. python内置函数 3.3. 高阶函数 4. 函数式编程的应用 Python函数式 ...

  5. Python常见的30个编程技巧,下手如有神助

    直接交换2个数字的位置 Python 提供了一种直观的方式在一行代码中赋值和交换(变量值).如下所示: x, y = 10, 20 print(x, y)x, y = y, x print(x, y) ...

  6. Python的22个编程技巧,Pick一下?你又知道多少呢……

    关注头条号,私信回复资料会有意外惊喜呦------最后一张照片有资料呦. 1. 原地交换两个数字 Python 提供了一个直观的在一行代码中赋值与交换(变量值)的方法,请参见下面的示例: x,y= 1 ...

  7. 编程软件python中的if用法-给Python初学者的一些编程技巧

    交换变量 x = 6 y = 5 x, y = y, x print x >>> 5 print y >>> 6 if 语句在行内 print "Hell ...

  8. 深入理解python特性_笔记《深入理解Python特性》PDF+编程技巧

    Python 技巧就是指一小段可以作为教学工具的代码,一个Python 技巧要么简要介绍了Python 的一个知识点,要么作为一个启发性的示例,让你自行深入挖掘,从而在大脑中形成直观的理解. 函数是P ...

  9. Python常用30个小技巧分享

    1.原地交换两个数字 x, y =10, 20 print(x, y) y, x = x, y print(x, y) 10 20 20 10 2.链状比较操作符 n = 10 print(1 < ...

  10. Python之禅与编程技巧

    Python 之禅 在学习 Python 全栈开发之前,早就听闻 "人生苦短,我用 Python" 的 Slogan,对于一个常年使用 C 的程序员,不亲身体验一把,真的很难想象 ...

最新文章

  1. PYTHON 写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者...
  2. 深度学习:垃圾自动分类
  3. qpython3下载-QPython3
  4. python脚本实例手机端-python调用adb脚本来实现群控安卓手机初探
  5. base64加密原理及python、C语言代码实现
  6. SAP的资产负债表、损益表的利润体现
  7. flink source 同步_如何生成 Flink 作业的交互式火焰图?
  8. Android Studio在Git上将项目推送到新的Url地址中
  9. 知乎个人精选 | 绝版的专业书到哪里找最快最高效?
  10. mvnrepository.com jar包下载
  11. matlab expotest,软硬件协同开发在电机控制的应用-matlabexpo2019.PDF
  12. 【转载】网络工程师行业的岗位认知
  13. 非线性微分方程线性化
  14. ubuntu16.04登录后只有蓝色背景解决方法
  15. 合并二叉树进行期权定价
  16. 影响职场升迁的小动作
  17. sql server 首字母大写
  18. 32位MD5加密 可用来微信加密
  19. Deepin-TIM或Deepin-QQ调整界面DPI字体大小的方法
  20. 汇编 eax test jnz jz 等组合连用的总结

热门文章

  1. 绅士游戏 android绅士在线阅读,一骑当千游戏,绅士游戏 android绅士
  2. 腾讯云uniapp云直播和即时通信插件接入流程
  3. CI/CD 流程以及原理
  4. 怎么进入计算机配置文件,老司机教你如何查看电脑配置
  5. 三大跳槽传闻,信了你就输了!
  6. Python学习笔记(15)-Python代码转换为exe可执行程序详解
  7. PAT 1010 月饼
  8. java 拦截器 排除_java – 如何将拦截器添加到除一个或两个以外的所有API请求?...
  9. 解决最近github网页无法打开问题
  10. excel 行列互换 绿色工具(怎么把行变成列,把列变成行)