Python盒子:模块、包和程序

命令行参数:

import sys
print('Program arguments:',sys.argv)

关于choice:

from random import choice
possibilities = ['rain', 'snow', 'sleet', 'fog', 'sun', 'who knows']
return choice(possibilities)

使用 int 是一种定义计数器的方式:

from collections import defaultdict
>>> food_counter = defaultdict(int)
>>> for food in ['spam', 'spam', 'eggs', 'spam']:
... food_counter[food] += 1
...
>>> for food, count in food_counter.items():
... print(food, count)
...
eggs 1
spam 3

上面的例子中,如果 food_counter 已经是一个普通的字典而不是 defaultdict 默认字典,
那每次试图自增字典元素 food_counter[food] 值时, Python 会抛出一个异常,因为我们没
有对它进行初始化。在普通字典中,需要做额外的工作,如下所示:

dict_counter = {}
>>> for food in ['spam', 'spam', 'eggs', 'spam']:
... if not food in dict_counter:
... dict_counter[food] = 0
... dict_counter[food] += 1
...
>>> for food, count in dict_counter.items():
... print(food, count)
...
spam 3
eggs 1

使用Counter()计数:

from collections import Counter
>>> breakfast = ['spam', 'spam', 'eggs', 'spam']
>>> breakfast_counter = Counter(breakfast)
>>> breakfast_counter
Counter({'spam': 3, 'eggs': 1})

函数 most_common() 以降序返回所有元素,或者如果给定一个数字,会返回该数字前的的
元素:

breakfast_counter.most_common()
[('spam', 3), ('eggs', 1)]
>>> breakfast_counter.most_common(1)
[('spam', 3)]

使用有序字典OrderedDict()按键排序:

from collections import OrderedDict
>>> quotes = OrderedDict([
... ('Moe', 'A wise guy, huh?'),
... ('Larry', 'Ow!'),
... ('Curly', 'Nyuk nyuk!'),
... ])
>>>
>>> for stooge in quotes:
... print(stooge)
...
Moe
Larry
Curly

双端队列: 栈+队列:

deque 是一种双端队列,同时具有栈和队列的特征。它可以从序列的任何一端添加和删除
项。现在,我们从一个词的两端扫向中间,判断是否为回文。函数 popleft() 去掉最左边
的项并返回该项, pop() 去掉最右边的项并返回该项。从两边一直向中间扫描,只要两端
的字符匹配,一直弹出直到到达中间:

def palindrome(word):
... from collections import deque
... dq = deque(word)
... while len(dq) > 1:
... if dq.popleft() != dq.pop():
... return False
... return True
...
...
>>> palindrome('a')
True
>>> palindrome('racecar')
104 | 第 5 章
True
>>> palindrome('')
True
>>> palindrome('radar')
True
>>> palindrome('halibut')
False

这里把判断回文作为双端队列的一个简单说明。如果想要写一个快速的判断回文的程
序,只需要把字符串反转和原字符串进行比较。 Python 没有对字符串进行反转的函数
reverse(),但还是可以利用反向切片的方式进行反转,如下所示:

>>> def another_palindrome(word):
... return word == word[::-1]
...
>>> another_palindrome('radar')
True
>>> another_palindrome('halibut')
False

使用pprint()友好输出:

from pprint import pprint
>>> quotes = OrderedDict([
... ('Moe', 'A wise guy, huh?'),
... ('Larry', 'Ow!'),
... ('Curly', 'Nyuk nyuk!'),
... ])
>>>

普通的 print() 直接列出所有结果:
>>> print(quotes)
OrderedDict([('Moe', 'A wise guy, huh?'), ('Larry', 'Ow!'), ('Curly', 'Nyuk nyuk!')])

但是, pprint() 尽量排列输出元素从而增加可读性:
>>> pprint(quotes)
{'Moe': 'A wise guy, huh?',
'Larry': 'Ow!',
'Curly': 'Nyuk nyuk!'}

 

posted @ 2017-05-21 21:11  livlovll  阅读(212)  评论(0)    收藏  举报