>>>print(a,b,c){'123','456'}[1,2,3,4](1,2,3,4,[1,3,2,1])>>>for i in a:...print(i)...123456>>>for i in b:...print(i)...1234>>>for i in c:...print(i)...1234[1,3,2,1]
2.2 遍历元素的同时,对索引进行遍历
Python中引入enumerate对索引(index)进行遍历,具体的使用方法如下:
>>> b
[1,2,3,4]>>>for i, k inenumerate(b):...print('id=', i,'value=', k)...id=0 value=1id=1 value=2id=2 value=3id=3 value=4
2.3 对字典(dict)键值对的遍历
for语句中的变量可以存在多个,这尤其体现在对字典的遍历中。
>>> d
{1:'a',2:'b','c':3}>>>for k in d:...print(k)...12
c
>>>for k, v in d.items():# 记得要加items()...print(k,':', v)...1: a
2: b
c :3
>>> a =range(1,11)>>> a
range(1,11)>>> a_set =set(a)# 隐式遍历>>> a_set
{1,2,3,4,5,6,7,8,9,10}>>>for i in a:# 显式遍历...print(i)...12345678910
4.2 隐式遍历与非遍历
由于隐式遍历的存在,可能会出现意料之外的情况,如下:
>>> a ="This is a test string.">>> a_set_1 =set(a)# 隐式遍历>>> a_set_2 ={a}# 非遍历>>> a_set_1, a_set_2
({'s','i','e','t','.','T',' ','n','g','h','r','a'},{'This is a test string.'})