Python: 早点知道这些就不会这样了

```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```

enumerate(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```

链式比较操作符

```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!```

collections.Counter

Python的集合库看上去是最好的。在计算需要集合中元素的个数时，StackOverflow找到的答案是创建有序字典，但我坚持使用一个代码片段来创建字典，计算结果中元素出现的频率。直到有一天，我发现可以用collections.deque。

```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```

字典推导

Python开发者的一个重要标志就是理解列表推导，但最终我发现字典推导也很有用，特别是在交换字典的键和值的时候。

```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"}```

用subprocess执行shell命令

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

```import os
os.system("dir")```

```import os
output = os.popen("dir")

字典的.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```

内省工具Introspection tools

```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```

685 篇文章131 人订阅

0 条评论

3598

36216

3386

2235

3506

21010

950

3086