30 tips & tricks for Python Programming

1  直接交换两个数字位置

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

2  比较运算符的链接

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

3  在条件语句中使用三元运算符

1 [on_true] if [expression] else [on_false]

这样可以使你的代码紧凑和简明。

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

同时,我们也可以在类对象中使用。

 x = (classA if y == 1 else classB)(param1, param2)

在上面的例子中,有两个类分别是类A和类B,其中一个类的构造函数将会被访问。下面的例子加入了评估最小数的条件。

 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)) #Output
#0 #1 #2 #3

我们甚至可以在一个列表生成器中使用三元运算符。

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

 #=> [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  多行字符串

使用反斜杠(backslashes)的基本方法最初来源于c语言,当然,我们熟悉的方法是使用三个引号(triple-quotes)

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

这样做的问题就是没有适当的缩进,如果缩进的话将会使空格也包含在字符串中,所以最终的解决方案就是把字符串分割成多行,把每行字符串放在引号中,然后将它们放在中括号中,如下:

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

5  在列表中存储变量

我们可以只用列表来初始化多个变量,拆开列表时,变量的数不应超过列表中元素的个数。

 testList = [1,2,3]
x, y, z = testList print(x, y, z) #-> 1 2 3

6  打印引入模块的文件路径

 import threading
import socket print(threading)
print(socket) #1- <module 'threading' from '/usr/lib/python2.7/threading.py'>
#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>

7  python的IDLE的交互式功能“_”

 >>> 2 + 1
3
>>> _
3
>>> print _
3

_下划线输出上次打印的结果

8  字典/集合生成器

 testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(10)} print(testSet)
print(testDict) #set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

9  调试脚本

我们可以使用pdb模块来为我们的脚本设置断点。

 import pdb
pdb.set_trace()

10  设置文件共享

Python允许你启动一个HTTP服务,你可以在服务的根目录中共享文件。

 # PYTHON 2
python -m SimpleHTTPServer
# PYTHON 3
python3 -m http.server

服务将启动默认的8000端口,你也可以在上面的命令中最后加上一个参数来自定义端口。

11  在Python中检查对象

简单的说就是使用dir()方法,用这个方法来查看这个对象的所有方法。

 test = [1, 3, 5, 7]
print( dir(test) )
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

12  简化if条件语句

为了验证多个值,我们可以试试一下方法:

 使用
if m in [1,3,5,7]:
而不是
if m==1 or m==3 or m==5 or m==7:

作为选择,我们可以在‘in’运算符后面使用‘{1,3,5,7}’代替‘[1,3,5,7]’因为 ‘set’ can access each element by O(1)。

13  在运行时检测Python版本

 import sys

 #Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
print("Sorry, you aren't running on Python 3.5\n")
print("Please upgrade to 3.5.\n")
sys.exit(1) #Print Python version in a readable format.
print("Current Python version: ", sys.version)

上面的代码中,你可以使用sys.version_info >= (3, 5)来代替sys.hexversion != 50660080。

当运行在Python2.7中时:

 Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux Sorry, you aren't running on Python 3.5 Please upgrade to 3.5.

当运行在Python3.5上时:

 Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05)
[GCC 5.3.0]

14 结合多个字符串

 test = ['I', 'Like', 'Python', 'automation']
print ''.join(test)

15  万能的逆转机制

#逆转列表
testList = [1, 3, 5]
testList.reverse()
print(testList) #-> [5, 3, 1] #在一个循环中反向迭代
for element in reversed([1,3,5]): print(element) #1-> 5
#2-> 3
#3-> 1 #字符串
"Test Python"[::-1] #使用切片反向列表
[1, 3, 5][::-1]

16  枚举器

 testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value) #1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30

17  使用枚举

 class Shapes:
Circle, Square, Triangle, Quadrangle = range(4) print(Shapes.Circle)
print(Shapes.Square)
print(Shapes.Triangle)
print(Shapes.Quadrangle) #1-> 0
#2-> 1
#3-> 2
#4-> 3

18  从函数中返回多个值

 # function returning multiple values.
def x():
return 1, 2, 3, 4 # Calling the above function.
a, b, c, d = x() print(a, b, c, d) #-> 1 2 3 4

19  使用星号运算符解包函数参数

 def test(x, y, z):
print(x, y, z) testDict = {'x': 1, 'y': 2, 'z': 3}
testList = [10, 20, 30] test(*testDict)
test(**testDict)
test(*testList) #1-> x y z
#2-> 1 2 3
#3-> 10 20 30

20  使用字典来存储表达式

 stdcalc = {
'sum': lambda x, y: x + y,
'subtract': lambda x, y: x - y
} print(stdcalc['sum'](9,3))
print(stdcalc['subtract'](9,3)) #1-> 12
#2-> 6

21  在任意一行数字中计算阶乘

#PYTHON 2.X.
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6 #PYTHON 3.X.
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result) #-> 6

22  在列表中找到出现次数最多的元素

 test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count)) #-> 4

23  重置递归次数限制

 import sys

 x=1001
print(sys.getrecursionlimit()) sys.setrecursionlimit(x)
print(sys.getrecursionlimit()) #1-> 1000
#2-> 1001

24  检查对象的内存使用

 #IN PYTHON 2.7.
import sys
x=1
print(sys.getsizeof(x)) #-> 24 #IN PYTHON 3.5.
import sys
x=1
print(sys.getsizeof(x)) #-> 28

25  使用 __slot__ 来减少内存开支

 import sys
class FileSystem(object): def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices print(sys.getsizeof( FileSystem )) class FileSystem1(object): __slots__ = ['files', 'folders', 'devices'] def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices print(sys.getsizeof( FileSystem1 )) #In Python 3.5
#1-> 1016
#2-> 888

显然,从结果中可以看到内存使用中有节省。但是你应该用__slots__当一个类的内存开销过大。只有在分析应用程序后才能做。否则,你会使代码难以改变,并没有真正的好处。

26  使用lambda处理打印

 import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
lprint("python", "tips",1000,1001) #-> python tips 1000 1001

27  通过两个相关序列创建字典

 t1 = (1, 2, 3)
t2 = (10, 20, 30) print(dict (zip(t1,t2))) #-> {1: 10, 2: 20, 3: 30}

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

 print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk"))) #1-> True
#2-> True

29  不使用任何循环形成一个统一的列表

 import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test))) #-> [-1, -2, 30, 40, 25, 35]

30  在Python中实现一个真正的切换实例声明

 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')) #1-> None
#2-> 2

转载翻译自http://www.techbeamers.com/essential-python-tips-tricks-programmers/

[转]Python程序员必须知道的30条编程技巧的更多相关文章

  1. Java程序员必须知道的10个调试技巧

    调试可以帮助识别和解决应用程序缺陷,在本文中,将使用大家常用的的开发工具Eclipse来调试Java应用程序. 但这里介绍的调试方法基本都是通用的,也适用于NetBeans IDE,我们会把重点放在运 ...

  2. CakePHP程序员必须知道的21条技巧

    这篇文章可以说是CakePHP 教程中最经典的了.虽然不是完整的手把手系列, 但作者将自己使用CakePHP 的经验总结了21条,这些尤其是对新手十分有用. 翻译时故意保留了一些CakePHP 中特有 ...

  3. 程序员必须知道的HTML常用代码有哪些?

    HTML即超文本标记语言,是目前应用最为广泛的语言之一,是组成一个网页的主要语言.在现今这个HTML5华丽丽地占领了整个互联网的时候,如果想要通过网页抓住浏览者的眼球光靠因循守旧是不行的,程序猿们需要 ...

  4. (转载) 据说年薪30万的Android程序员必须知道的

    据说年薪30万的Android程序员必须知道的帖子 标签: android 2015-03-12 16:52 28705人阅读 评论(14) 收藏 举报 Android中国开发精英 目前包括: And ...

  5. 程序员必须知道的git托管平台

    http://www.open-open.com/lib/view/open1420704561390.html

  6. (转)Java程序员应该知道的10个调试技巧

    (转自 酷勤网 – 程序员的那点事!http://www.kuqin.com/) 试可以帮助识别和解决应用程序缺陷,在本文中,作者将使用大家常用的的开发工具Eclipse来调试Java应用程序.但这里 ...

  7. 程序员必需知道的Mac OS使用技巧

    macos sierra正式版发布了,于是我把我沉寂了一年没有用过了的macbook拿出来玩玩,顺便把一些常用技巧mark. 1.apple store下载软件无响应(经常出现的问题) 解决方法:更改 ...

  8. 学python必须知道的30个技巧

    收集这些有用的捷径技巧 1. 原地进行交换两个数字 我们对赋值的右侧进行一个新的元组,左侧解析(unpack)那个(未被引用的)元组到变量 <a> 和 <b> 赋值完成时,新的 ...

  9. App运营者必须知道的30款数据分析工具

    如今的移动应用早已不再是某种结构单一.功能简单的工具了.当我们的移动应用变得越来越庞杂,我们便会需要借用分析工具,来跟踪和分析App内的每一个部分.幸运的是,目前市面上有许多数据分析工具可供App开发 ...

随机推荐

  1. java web _BBS

    在注册时用户输入用户名和密码不合格在旁边提示 在用户发言带有屏蔽字时应在旁边提示,但不影响其发送,只是在显示时屏蔽关键字

  2. App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure.-解决办法

    运行环境:Xcode Version 7.3.1 (7D1014) 使用NSURL进行数据请求数据代码: -(NSData *)requestData{ NSURL *url = [NSURL URL ...

  3. C# 特性详解

    特性(attribute)是被指定给某一声明的一则附加的声明性信息. 在C#中,有一个小的预定义特性集合. using System; public class AnyClass { [Obsolet ...

  4. #error作用

    指令 用途 # 空指令,无任何效果 #include 包含一个源代码文件 #define 定义宏 #undef 取消已定义的宏 #if 如果给定条件为真,则编译下面代码 #ifdef 如果宏已经定义, ...

  5. hive查看建表语句

    查看hive建表语句:show create table tablename; 查看hive表结构:describe  tablename; 简写:desc tablename;

  6. HttpURLConnection下载图片的两种方式

    public class MainActivity extends AppCompatActivity { private ImageView iv; private String imageurl ...

  7. solrCloud 管理

    创建collection: /soft/server/solr-4.10.0/example/scripts/cloud-scripts/zkcli.sh -cmd upconfig -zkhost ...

  8. MySQL Innodb的两种表空间方式

    要说表空间,MySQL的表空间管理远远说不上完善.换句话说,事实上MySQL根本没有真正意义上的表空间管理.MySQL的Innodb包含两种表空间文件模式,默认的共享表空间和每个表分离的独立表空间.只 ...

  9. 第三方控件radupload 使用方式以及报错处理

    使用方式: 1.web.config  中需要加入: <httpHandlers>    <add verb="*" path="Telerik.Rad ...

  10. Linux内核分析第六周学习总结:进程的描述和进程的创建

    韩玉琪 + 原创作品转载请注明出处 + <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 一.进程的描述 ...