同时迭代两个列表
nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
print teama + " vs. " + teamb
>>> Packers vs. Ravens
>>> 49ers vs. Patriots
初始化列表的值
items = [0]*3
print items
>>> [0,0,0]
列表转换为字符串
teams = ["Packers", "49ers", "Ravens", "Patriots"]
print ", ".join(teams)
>>> 'Packers, 49ers, Ravens, Patriots'
从字典中获取元素
data = {'user': 1, 'name': 'Max', 'three': 4}
try:
is_admin = data['admin']
except KeyError:
is_admin = False
替换成这样
data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = data.get('admin', False)
计数时使用Counter计数对象
这听起来显而易见,但经常被人忘记。对于大多数程序员来说,数一个东西是一项很常见的任务,而且在大多数情况下并不是很有挑战性的事情——这里有几种方法能更简单的完成这种任务。
Python的collections类库里有个内置的dict类的子类,是专门来干这种事情的:
>>> from collections import Counter
>>> c = Counter('hello world')
>>> c
Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})
>>> c.most_common(2)
[('l', 3), ('o', 2)]
迭代工具
和collections库一样,还有一个库叫itertools,对某些问题真能高效地解决。其中一个用例是查找所有组合,他能告诉你在一个组中元素的所有不能的组合方式
from itertools import combinations
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
print game
>>> ('Packers', '49ers')
>>> ('Packers', 'Ravens')
>>> ('Packers', 'Patriots')
>>> ('49ers', 'Ravens')
>>> ('49ers', 'Patriots')
>>> ('Ravens', 'Patriots')
网友评论