1、变量交换
>>> a, b = b, a
2、循环遍历区间元素
for i in xrange(6):
(print i)
3、带有索引位置的集合遍历
colors = ['red', 'green', 'blue', 'yellow']
for i, color in enumerate(colors):
print (i, '--->', color)
4、字符串连接
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
print (', '.join(names))
5、打开关闭文件
with open('data.txt') as f:
data = f.read()
上述方法比f = open('data.txt')更安全,
read、readlines、readline的区别
read 读取整个文件
readline 读取下一行
readlines 读取整个文件到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便),文件较大时会占用内存
6、列表推导式
[i*2 for i in xrange(10)]
7、合理使用列表
列表对象(list)是一个查询效率高于更新操作的数据结构,比如删除一个元素和插入一个元素时执行效率就非常低,因为还要对剩下的元素进行移动
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
names.pop(0)
names.insert(0, 'mark')
pythonic
from collections import deque
names = deque(['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie'])
names.popleft()
names.appendleft('mark')
deque 是一个双向队列的数据结构,删除元素和插入元素会很快
8、遍历字典的 key 和 value
方法一速度没那么快,因为每次迭代的时候还要重新进行hash查找 key 对应的 value。
方法二遇到字典非常大的时候,会导致内存的消耗增加一倍以上
# 方法一
for k in d:
print (k, '--->', d[k])
# 方法二
for k, v in d.items():
print (k, '--->', v)
pythonic
for k, v in d.iteritems():
print (k, '--->', v)
iteritems 返回迭代器对象,可节省更多的内存,不过在 python3 中没有该方法了,只有 items 方法,等值于 iteritems。
9、遍历一个集合
colors = ['red', 'green', 'blue', 'yellow']
for color in colors: print color
10、反向遍历
for color in reversed(colors): print color
11、遍历两个集合
for name, color in izip(names, colors): print name, '--->', color
12、在循环内识别多个退出点
def find(seq, target): for i, value in enumerate(seq): if value == target: break else: return -1 return i
for
执行完所有的循环后就会执行else
。
把else
记成nobreak
,当for
没有被break
,那么循环结束时会进入到else
。
13、遍历字典的key
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
for k in d:
print k
for k in d.keys():
if k.startswith('r'):
del d[k]
什么时候应该使用第二种而不是第一种方法?当你需要修改字典的时候。
如果你在迭代一个东西的时候修改它,那就是在冒天下之大不韪,接下来发生什么都活该。
d.keys()
把字典里所有的key都复制到一个列表里。然后你就可以修改字典了。
14、用key value点对构建字典
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']
d = dict(izip(names, colors))
# {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
15、用字典计数
colors = ['red', 'green', 'red', 'blue', 'green', 'red'] # 简单,基本的计数方法。适合初学者起步时学习。 d = {} for color in colors: if color not in d: d[color] = 0 d[color] += 1 # {'blue': 1, 'green': 2, 'red': 3}
16、用字典分组
names = ['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'] # 在这个例子,我们按name的长度分组 d = {} for name in names: key = len(name) if key not in d: d[key] = [] d[key].append(name) # {5: ['roger', 'betty'], 6: ['rachel', 'judith'], 7: ['raymond', 'matthew', 'melissa', 'charlie']}
17、字典的popitem()
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
while d:
key, value = d.popitem()
print key, '-->', value
Python 字典 popitem() 方法随机返回并删除字典中的一对键和值。 如果字典已经为空,却调用了此方法,就报出KeyError异常。