在字典中循环时,关键字和对应的值可以使用 items() 方法同时解读出来:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items(): #for k,v inXXX 实际是K对应键,v对应值
print(k, v)#同时输出了K(键)和V(值)而且是按顺序输出键值对
在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v) ...
0 tic
1 tac
2 toe
同时循环两个或更多的序列,可以使用 zip() 整体打包:
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
需要逆向循环序列的话,先正向定位序列,然后调用 reversed() 函数:
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
要按排序后的顺序循环序列的话,使用 sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
del 语句
有个方法可以从列表中按给定的索引而不是值来删除一个子项: del 语句。它不同于有返回值的 pop() 方法。
语句 del 还可以从列表中删除切片或清空整个列表(我们以前介绍过一个方法是将空列表赋值给列表的切片)。
例如:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a [1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a [1, 66.25, 1234.5]
>>> del a[:]
>>> a []
del 也可以删除整个变量:
>>> del a
此后再引用命名 a 会引发错误(直到另一个值赋给它为止)。我们在后面的内容中可以看到 del 的其它用法。