用法:对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值;
常用for循环打印:
1 seq = [1,2,3] 2 for index, item in enumerate(seq): 3 print(index, item)
输出:
0 1
1 2
2 3
一些练习:
列表见上例;
1 # 元组 2 # tup = (a,b,c)将报错,因为不用‘’引起来的话,系统将认为a,b,c是变量名,报错:未定义 3 tup = ('a','b','c') 4 for index, item in enumerate(tup): 5 print(index, item) 6 # 输出: 7 0 a 8 1 b 9 2 c
# 字符串 strs = "abc" for index, item in enumerate(tup): print(index, item) # 输出 0 a 1 b 2 c
# 字典 goods_list = {'House':1000000, 'Furniture':300000, 'Food':50000, 'Travel':50000} print(goods_list) {'House': 1000000, 'Furniture': 300000, 'Food': 50000, 'Travel': 50000} for index, item in enumerate(goods_list): print(index, item) # 输出 0 House 1 Furniture 2 Food 3 Travel
1 # 列表套元组 2 goods_list = [('House',1000000),('Furniture',300000),('Food',50000),('Travel',300000)] 3 for index, item in enumerate(goods_list): 4 print(index, item) 5 输出: 6 0 ('House', 1000000) 7 1 ('Furniture', 300000) 8 2 ('Food', 50000) 9 3 ('Travel', 300000)