博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于python - 更优雅的技巧
阅读量:4562 次
发布时间:2019-06-08

本文共 3429 字,大约阅读时间需要 11 分钟。

枚举

不要这么做:

i = 0for item in iterable:    print i, item    i += 1

而是这样:

for i, item in enumerate(iterable):    print i, item

enumerate可以接受第二个参数,例如:

>>> list(enumerate('abc'))[(0, 'a'), (1, 'b'), (2, 'c')]>>> list(enumerate('abc', 1))[(1, 'a'), (2, 'b'), (3, 'c')]

字典/集合 解析

你可能知道列表解析,但不知道字典/集合解析。字典/集合解析简单而且高效,例如:

my_dict = {i: i * i for i in xrange(100)}my_set = {i * 15 for i in xrange(100)}# There is only a difference of ':' in both

强制浮点数除法

如果我们除以一个整数,即使结果是一个浮点数,Python(2) 依旧会给我们一个整数。为了规避这个问题,我们需要这样做:

result = 1.0/2

但是现在有一种别的方法可以解决这个问题,甚至在之前我都没有意识到有这种方法存在。你可以进行如下操作:

from __future__ import divisionresult = 1/2# print(result)# 0.5

需要注意的是这个窍门只适用于Python 2。在Python 3 中就不需要进行import 操作了,因为它已经默认进行import了。

简单的服务器

你想快速简单的分享目录下的文件吗?可以这样做:

# Python2python -m SimpleHTTPServer# Python 3python3 -m http.server

这回启动一个服务器

Python表达式求值

我们都知道eval,但也许并不是所有人都知道literal_eval.可以这么做:

import astmy_list = ast.literal_eval(expr)

而不是这样:

expr = "[1, 2, 3]"my_list = eval(expr)

我相信对于大多数人来说这种形式是第一次看见,但是实际上这个在Python中已经存在很长时间了。

分析脚本

按下面的方式运行脚本,可以很简单的对其进行分析:

python -m cProfile my_script.py

对象自检

在Python中,可以通过dir()来检查对象,例如:

>>> foo = [1, 2, 3, 4]>>> dir(foo)['__add__', '__class__', '__contains__','__delattr__', '__delitem__', '__delslice__', ... ,'extend', 'index', 'insert', 'pop', 'remove','reverse', 'sort']

调试脚本

你可以使用pdb模块在脚本中设置断点来调试脚本,就像这样:

import pdbpdb.set_trace()

你可以在脚本的任何地方加入pdb.set_trace(),该函数会在那个位置设置一个断点。超级方便。你应该多阅读 函数的相关内容,因为在它里面还有很多鲜为人知的功能。

 

简化if结构

如果必须检查一些值,可以用

if n in [1,4,5,6]:

而不是用复杂的if结构:

if n==1 or n==4 or n==5 or n==6:

字符串/数列 逆序

下面的方式可以快速反转一个列表:

>>> a = [1,2,3,4]>>> a[::-1][4, 3, 2, 1]# This creates a new reversed list.# If you want to reverse a list in place you can do:a.reverse()

这种方式同样适用于字符串:

>>> foo = "yasoob">>> foo[::-1]'boosay'

优雅地打印

下面的方式pprint可以用优雅的方式打印字典和列表:

from pprint import pprintpprint(my_dict)

这用于字典打印是非常高效的,如果你想从文件中快速优雅的打印出json,可以这样做:

cat file.json | python -m json.tools

 

三元运算

三元运算是if-else 语句的快捷操作,也被称为条件运算。这里有几个例子可以供你参考:

[on_true] if [expression] else [on_false]x, y = 50, 25small = x if x < y else y

除法相关

  •  求商、求余

>>> divmod(5, 2)

(2, 1)

  • 四舍五入

>>> round(5/2)

3.0

字符串相关

  • ord()能够返回某个字符所对一个的ASCII值(是十进制的),字符a在ASCII中的值是97,空格在ASCII中也有值,是32。

    反过来,根据整数值得到相应字符,可以使用chr()。

>>> ord('a')

97

>>> chr(99)

'c'

 编码问题

  • error---'ascii' codec can't encode characters in position

>>> import sys

>>> sys.getdefaultencoding()
'ascii'

>>> sys.setdefaultencoding()

Traceback (most recent call last):

File "<pyshell#2>", line 1, in <module>
sys.setdefaultencoding()
AttributeError: 'module' object has no attribute 'setdefaultencoding'
>>> reload(sys)
>>> sys.setdefaultencoding('utf-8')

 "AttributeError: 'module' object has no attribute 'setdefaultencoding'"  why  ???

:

"""Append module search paths for third-party packages to sys.path."""
* This module is automatically imported during initialization. *
def setencoding():    """Set the string encoding used by the Unicode implementation.     The  default is 'ascii', but if you're willing to experiment, you can change this.   """   encoding = "ascii" # Default value set by _PyUnicode_Init()
def main():
  ......     # Remove sys.setdefaultencoding() so that users cannot change the    # encoding after initialization. The test for presence is needed when    # this module is run as a script, because this code is executed twice.   if hasattr(sys, "setdefaultencoding"):     del sys.setdefaultencoding 参考链接:
(1)源码参见
(2)编码问题更多可参考 (3)

 

转载于:https://www.cnblogs.com/tangkaixin/p/4404668.html

你可能感兴趣的文章
汽车之家面试题2016
查看>>
POJ-数据结构-优先队列模板
查看>>
【HAOI2006】旅行(并查集暴力)
查看>>
css实现文本超出部分省略号显示
查看>>
留言板
查看>>
vue-router组件状态刷新消失的问题
查看>>
Android UI开发第十四篇——可以移动的悬浮框
查看>>
java8的一些用法
查看>>
(十)Hive分析窗口函数(二) NTILE,ROW_NUMBER,RANK,DENSE_RANK
查看>>
2018-11-19站立会议内容
查看>>
第五次作业 关于《构建之法》的心得体会
查看>>
Memo打印1
查看>>
AtCoder Grand Contest 010 --C:Cleaning
查看>>
Memcached 笔记与总结(3)安装 php-memcache(windows 系统下)
查看>>
Android2.2中添加的match_parent和fill_parent没有区别
查看>>
POJ 1251 Jungle Roads (prim)
查看>>
IOS_画图 图片等比压缩 IOS_UIImage
查看>>
刘关张三结义(第七次作业)
查看>>
Redis学习笔记(十一) 命令进阶:Connection(连接)
查看>>
memcached与redis 对比
查看>>