python 杂读笔记

python 有用的代码段

漂亮的打印


import pprint as pp
animals = [{'animal': 'dog', 'legs': 4, 'breeds': ['Border Collie', 'Pit Bull', 'Huskie']}, {'animal': 'cat', 'legs': 4, 'breeds': ['Siamese', 'Persian', 'Sphynx']}]
pp.pprint(animals, width=1)

import json
json.dumps(animals, indent=3)

删除列表重复的元素

缺点没有顺序


x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
list(set(x))

解决上面没有顺序的问题


from collections import OrderedDict
x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
list(OrderedDict.fromkeys(x))


for 通过索引访问数组


x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
for index, value in enumerate(x, start=1):
    print(index, value)

Stop writing code that will break on Python 4!

目前python 2,3兼容相关方面的写法


import six

for item in six.iteritems(dictionary):
    # code here


if six.PY3:
    # Python 3 code
else:
    # Python 2 code


if six.PY2:
    # Python 2 code
elif six.PY3:
    # Python 3 code


总结看来使用这种方法不太行,转而使用six模块,six模块解决大部份兼容性问题!

python 2 3 变动

  1. 语法变动
  2. 模块命名

six模块(Python 2 and 3 Compatibility Library)

名字由来 The name, “six”, comes from the fact that 2*3 equals 6.

字典

  1. six.iterkeys(dictionary, **kwargs)
  2. six.itervalues(dictionary, **kwargs)
  3. six.iteritems(dictionary, **kwargs)
  4. six.iterlists(dictionary, **kwargs)

前面4 个都因为python 3 不用iterm的前缀所致!

  1. six.viewkeys(dictionary)
  2. six.viewvalues(dictionary)
  3. six.viewitems(dictionary)

前面3个都因为python 3 不用view的前缀所致!

Binary and text data

变动

  1. stringio > io six.StringIO six.BytesIO

Renamed modules and attributes compatibility

  1. tkinter
  2. urllib
  3. html
  4. urlparse

总结如此之多,因此不可能记起,试试使用2to3帮助下!

记法: 字典,io,url!

原文地址

Useful Python Snippets

six

Loading Disqus comments...
Table of Contents