必须掌握的Python循环技巧
1、在字典中,用items()取出键和对应值
>>> king = {'name':'zxb','sex':'man','age':'18'}
>>> for k,v in king.items():
... print(k,v)
...
name zxb
sex man
age 18
>>>
2、在序列中循环时,使enumerate()函数可以同时取出位置索引和对应值
>>> arr = ['a','b','c']
>>> for i,v in enumerate(arr):
... print(i,v)
...
0 a
1 b
2 c
>>>
3、同时循环两个或多个序列时,用zip()函数可以将其内的元素一一匹配
>>> questions = ['name','age','sex']
>>> answers = ['zxb','18','man']
>>> for q,a in zip(questions,answers):
... print('what is your {0}? It is {1}'.format(q,a))
...
what is your name? It is zxb
what is you rage? It is 18
what is your sex? It is man
>>>
4、使用reverse函数逆向循环序列
>>> for i in reversed(range(1,10,2)):
... print(i)
...
9
7
5
3
1
>>>
5、按指定顺序循环序列,可以用sorted()函数,在不改动原序列基础上,返回一个新的序列
>>> zero = ['a','z','b','e','c']
>>> for i in sorted(zero):
... print(i)
...
a
b
c
e
z
>>>
6、使用set()去除列表中的重复元素。使用sorted()加set()则按排序后的顺序,循环遍历序列中的唯一元素
>>> zero = ['a','z','b','e','c','a','c']
>>> for i in sorted(set(zero)):
... print(i)
...
a
b
c
e
z
>>>
7、一般来说,在循环中修改列表的内容时,创建新列表比较简单
>>> import math
>>> arr = [56.5,float('NaN'),32.3]
>>> newArr = []
>>> for value in arr:
... if not math.isnan(value):
... newArr.append(value)
...
>>> newArr
[56.5, 32.3]
>>>
其中 math.isnan()表示是否为预定义常数
|