# 10个应该早点知道的Python技巧

## 1. 在Python 2中Python 3风格的打印输出

mynumber = 5

print "Python 2:"
print "The number is %d" % (mynumber)
print mynumber / 2,
print mynumber // 2

from __future__ import print_function
from __future__ import division

print('\nPython 3:')
print("The number is {}".format(mynumber))
print(mynumber / 2, end=' ')
print(mynumber // 2)

Python 2:
The number is 5
2 2

Python 3:
The number is 5
2.5 2

Oh,这里有个给C程序员的彩蛋：

from __future__ import braces

File "<ipython-input-3-2aebb3fc8ecf>", line 1
from __future__ import braces
SyntaxError: not a chance

## 2. 枚举(list)

mylist = ["It's", 'only', 'a', 'model']

for index, item in enumerate(mylist):
print(index, item)

0 It's
1 only
2 a
3 model

## 3.连续比较操作

mynumber = 3

if 4 > mynumber > 2:
print("Chained comparison operators work! \n" * 3)

Chained comparison operators work!
Chained comparison operators work!
Chained comparison operators work!

## 4. collections.Counter

from collections import Counter
from random import randrange
import pprint
mycounter = Counter()
for i in range(100):
random_number = randrange(10)
mycounter[random_number] += 1
for i in range(10):
print(i, mycounter[i])

0 10
1 10
2 13
3 6
4 6
5 11
6 10
7 14
8 12
9 8

## 5. 字典解析

my_phrase = ["No", "one", "expects", "the", "Spanish", "Inquisition"]
my_dict = {key: value for value, key in enumerate(my_phrase)}
print(my_dict)
reversed_dict = {value: key for key, value in my_dict.items()}
print(reversed_dict)

{'Inquisition': 5, 'No': 0, 'expects': 2, 'one': 1, 'Spanish': 4, 'the': 3}
{0: 'No', 1: 'one', 2: 'expects', 3: 'the', 4: 'Spanish', 5: 'Inquisition'}

## 6. 用subprocess执行shell命令

import subprocess
output = subprocess.check_output('dir', shell=True)
print(output)

Volume in drive C is OS
Volume Serial Number is [REDACTED]
Directory of C:\Users\David\Documents\[REDACTED]

2014-11-26  06:04 AM    <DIR>          .
2014-11-26  06:04 AM    <DIR>          ..
2014-11-23  11:47 AM    <DIR>          .git
2014-11-26  06:06 AM    <DIR>          .ipynb_checkpoints
2014-11-23  08:59 AM    <DIR>          CCCma
2014-09-03  06:58 AM            19,450 colorbrewdict.py
2014-09-03  06:58 AM            92,175 imagecompare.ipynb
2014-11-23  08:41 AM    <DIR>          Japan_Earthquakes
2014-09-03  06:58 AM             5,263 monty_monte.ipynb
2014-09-03  06:58 AM            31,082 pocket_tumblr_reddit_api.ipynb
2014-11-26  06:14 AM            19,898 top_10_python_idioms.ipynb
2014-09-03  06:58 AM             5,813 tree_convert_mega_to_gexf.ipynb
2014-09-03  06:58 AM             5,453 tree_convert_mega_to_json.ipynb
2014-09-03  06:58 AM             1,211 tree_convert_newick_to_json.py
2014-09-03  06:58 AM            55,970 weather_ML.ipynb
11 File(s)        240,626 bytes
6 Dir(s)  180,880,490,496 bytes free

## 7. dict .get() 和 .iteritems() 方法

my_dict = {'name': 'Lancelot', 'quest': 'Holy Grail', 'favourite_color': 'blue'}

print(my_dict.get('airspeed velocity of an unladen swallow', 'African or European?\n'))

for key, value in my_dict.iteritems():
print(key, value, sep=": ")

African or European?

quest: Holy Grail
name: Lancelot
favourite_color: blue

a = 'Spam'
b = 'Eggs'

print(a, b)

a, b = b, a

print(a, b)

Spam Eggs
Eggs Spam

## 9. 内省工具

my_dict = {'That': 'an ex-parrot!'}

help(my_dict)

Help on dict object:

class dict(object)
|  dict() -> new empty dictionary
|  dict(mapping) -> new dictionary initialized from a mapping object's
|      (key, value) pairs
|  dict(iterable) -> new dictionary initialized as if via:
|      d = {}
|      for k, v in iterable:
|          d[k] = v
|  dict(**kwargs) -> new dictionary initialized with the name=value pairs
|      in the keyword argument list.  For example:  dict(one=1, two=2)
|
|  Methods defined here:
|
|  __cmp__(...)
|      x.__cmp__(y) <==> cmp(x,y)
|
|  __contains__(...)
|      D.__contains__(k) -> True if D has a key k, else False
|
|  __delitem__(...)
|      x.__delitem__(y) <==> del x[y]
|
|  __eq__(...)
|      x.__eq__(y) <==> x==y
|

[TRUNCATED FOR SPACE]

|
|  update(...)
|      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
|      If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
|      If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
|      In either case, this is followed by: for k in F: D[k] = F[k]
|
|  values(...)
|      D.values() -> list of D's values
|
|  viewitems(...)
|      D.viewitems() -> a set-like object providing a view on D's items
|
|  viewkeys(...)
|      D.viewkeys() -> a set-like object providing a view on D's keys
|
|  viewvalues(...)
|      D.viewvalues() -> an object providing a view on D's values
|
|  ----------------------------------------------------------------------
|  Data and other attributes defined here:
|
|  __hash__ = None
|
|  __new__ =
|      T.__new__(S, ...) -> a new object with type S, a subtype of T

## 10. PEP-8 兼容字符串链

PEP8 是Python编程风格指南。除其他事项外，它建议每一行不要超过80个字符，并且保持换行缩进一致。

my_long_text = ("We are no longer the knights who say Ni! "
"We are now the knights who say ekki-ekki-"
"ekki-p'tang-zoom-boing-z'nourrwringmm!")
print(my_long_text)

We are no longer the knights who say Ni! We are now the knights who say ekki-ekki-ekki-p'tang-zoom-boing-z'nourrwringmm!

1311 篇文章122 人订阅

0 条评论

## 相关文章

38270

14410

294100

11020

13440

9220

10630

### 深入理解计算机系统（2.1）------信息的存储和表示

前面我们介绍了《深入理解计算机系统》第一章的内容----计算机系统漫游。包括简单介绍了 Hello World 程序在计算机中是如何运行的，存储设备的层次结...

24480

32220

### 10种简单的Java性能优化学习

10种简单的Java性能优化学习 你是否正打算优化hashCode()方法？是否想要绕开正则表达式？Lukas Eder介绍了很多简单方便的性能优化小贴士以及扩...

35860