Python enumerate() 函数
描述:
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法:
enumerate(sequence, [start=0])
参数:
- sequence -- 一个序列、迭代器或其他支持迭代对象。
 - start -- 下标起始位置。
 
实例一:
使用普通for循环
i = 0
seq = ['one', 'two', 'three']
for element in seq:
    print i, seq[i]
    i +=1
使用含enumerate的for循环
i = 0
seq = ['one', 'two', 'three']
for element in enumerate(seq):
    print i, seq[i]
实例二:
假设我们有一群人参加舞蹈比赛,为了公平起见,我们要随机排列他们的出场顺序。我们下面利用random包和enumerate函数实现:
import random
all_people = ['Tom', 'Vivian', 'Paul', 'Liya', 'Manu', 'Daniel', 'Shawn']
random.shuffle(all_people)
for i,name in enumerate(all_people):
    print(i,':'+name)
    ——纸月永远在路上~
                    
                
                
            
        
浙公网安备 33010602011771号