文档说明: 整理了部分Python2.7版本新增特性,以及与Python3.x的一些特性对比
参考资料:https://docs.python.org/2/whatsnew/2.7.html#what-s-new-in-python-2-7
Python 2.7于2010年7月3日发布,原计划在2015年终止支持,但由于大量代码没有移植到Python 3,Python语言作者Guido van Rossum将终止支持的时间推迟到了2020年。用户如果想要在这个日期之后继续得到与Python 2.7有关的支持,则需要付费给商业供应商
优化
- 浮点数和十进制类,数字处理
- 标准库:unittest、argparse、collections等等
PEP 372: Adding an Ordered Dictionary to collections
Python字典(dict),Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。OrderedDict API提供了与常规字典相同的接口,但根据首次插入键的时间,按保证的顺序迭代键和值
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
... ('second', 2),
... ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
如果重新赋值一个现有的字典值,原始插入位置保持不变
>>> d['second'] = 4
>>> d.items()
[('first', 1), ('second', 4), ('third', 3)]
删除后再重新插入,自动排到最后
>>> del d['second']
>>> d['second'] = 5
>>> d.items()
[('first', 1), ('third', 3), ('second', 5)]
popitem()方法 可以实现一个FIFO(先进先出)的dict,last默认值为True,删除最后一个参数,如果为false,则删除最早添加的参数
>>> od = OrderedDict([(x,0) for x in range(20)])
>>> print od
OrderedDict([(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0), (14, 0), (15, 0), (16, 0), (17, 0), (18, 0), (19, 0)])
>>> od.popitem()
(19, 0)
>>> od.popitem(last=False)
(0, 0)
>>> print od
OrderedDict([(1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0), (14, 0), (15, 0), (16, 0), (17, 0), (18, 0)])
比较两个有序字典的键和值,并要求插入顺序相同
>>> od1 = OrderedDict([('first', 1), ('second', 2), ('third', 3)])
>>> od2 = OrderedDict([('third', 3), ('first', 1),('second', 2)])
>>> od1 == od2
False
>>> # Move 'third' key to the end
>>> del od2['third']; od2['third'] = 3
>>> od1 == od2
True
PEP 378: Format Specifier for Thousands Separator
为了使程序输出更具可读性,可以向较大的数字添加分隔符,格式化浮点数时,只需在宽度和精度之间加上逗号
>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'
格式化整数时,在宽度后面加上逗号
>>> '{:20,d}'.format(18446744073709551616)
'18,446,744,073,709,551,616'
PEP 389: The argparse Module for Parsing Command Lines
2.7之后python不再对optparse模块进行扩展,推荐使用argparse模块对命令行进行解析
import argparse
parser = argparse.ArgumentParser(description='Command-line example.')
# Add optional switches
parser.add_argument('-v', action='store_true', dest='is_verbose',
help='produce verbose output')
parser.add_argument('-o', action='store', dest='output',
metavar='FILE',
help='direct output to FILE instead of stdout')
parser.add_argument('-C', action='store', type=int, dest='context',
metavar='NUM', default=0,
help='display NUM lines of added context')
# Allow any number of additional arguments.
parser.add_argument(nargs='*', action='store', dest='inputs',
help='input filenames (default is stdin)')
args = parser.parse_args()
print args.__dict__
内置 - h 和 --help 帮助文档:
-> ./python.exe argparse-example.py --help
usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Command-line example.
positional arguments:
inputs input filenames (default is stdin)
optional arguments:
-h, --help show this help message and exit
-v produce verbose output
-o FILE direct output to FILE instead of stdout
-C NUM display NUM lines of added context
PEP 391: Dictionary-Based Configuration For Logging
Python 2.7增加了一个dictConfig()函数,支持字典、包含JSON解析文件、或者YAML解析库等等方法配置日志记录
import logging
import logging.config
configdict = {
'version': 1, # Configuration schema in use; must be 1 for now
'formatters': {
'standard': {
'format': ('%(asctime)s %(name)-15s '
'%(levelname)-8s %(message)s')}},
'handlers': {'netlog': {'backupCount': 10,
'class': 'logging.handlers.RotatingFileHandler',
'filename': '/logs/network.log',
'formatter': 'standard',
'level': 'INFO',
'maxBytes': 1000000},
'syslog': {'class': 'logging.handlers.SysLogHandler',
'formatter': 'standard',
'level': 'ERROR'}},
# Specify all the subordinate loggers
'loggers': {
'network': {
'handlers': ['netlog']
}
},
# Specify properties of the root logger
'root': {
'handlers': ['syslog']
},
}
# Set up configuration
logging.config.dictConfig(configdict)
# As an example, log two error messages
logger = logging.getLogger('/')
logger.error('Database not found')
netlogger = logging.getLogger('network')
netlogger.error('Connection failed')
PEP 3106: Dictionary Views
Pthon 2.7里,字典返回的是一个视图对象,而不是一个实例化的列表,viewkeys(),viewvalues(), viewitems() ;在Python3.x版本,废弃了2.7的方法,改为 keys(),values(), items() 。
>>> d = dict((i*10, chr(65+i)) for i in range(26))
>>> d
{0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
>>> d.viewkeys()
dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
遍历viewkeys()对象
>>> d1 = dict((i*10, chr(65+i)) for i in range(26))
>>> d2 = dict((i**.5, i) for i in range(1000))
>>> d1.viewkeys() & d2.viewkeys()
set([0.0, 10.0, 20.0, 30.0])
>>> d1.viewkeys() | range(0, 30)
set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
PEP 3137: The memoryview Object
以下实例展示了 memoryview 的使用方法
Python2.7 应用
>>>v = memoryview('abcefg')
>>> v[1]
'b'
>>> v[-1]
'g'
>>> v[1:4]
<memory at 0x77ab28>
>>> v[1:4].tobytes()
'bce'
Python3.x 应用
>>>v = memoryview(bytearray("abcefg", 'utf-8'))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b'bce'
其他变化
在一个上下文管理器中声明多个上下文管理器,上下文管理器处理从左至右,每一个与声明视为一个新的开始。
with A() as a, B() as b:
... suite of statements ...
# 相当于
with A() as a:
with B() as b:
... suite of statements ...
Python 2.7的浮点对比2.6有更高的精度
>>> n = 295147905179352891391
>>> float(n)
2.9514790517935289e+20
>>> n - long(float(n))
-1L
str.format()方法替代% s字符串格式化
>>> '{}:{}:{}'.format(2009, 04, 'Sunday')
'2009:4:Sunday'
>>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
'2009:4:Sunday'
网友评论