s = ['a','b','c'] print (enumerate(s))
返回一个对象,该对象内的值需要一个个输出,这里整串输出会直接打印出对象本身
>> <enumerate object at 0x10aa31cd0>
以列表的形式输出:
s = ['a','b','c'] print(list(enumerate(s)))
返回:[(0, 'a'), (1, 'b'), (2, 'c')]
通过下标循环访问列表元素,没用enumerate只能直接访问元素无法从使用下标
l = ['a','b','c'] e = enumerate(l) for i,e in e: print i,e
返回:下标和对应的值0 a 1 b 2 c
l = ['a','b','c'] e = enumerate(l) for i in e: print i
返回:带下标的每个数据
(0, 'a') (1, 'b') (2, 'c')
# 列表包含字典,然后进行enumerate后每个元素有3个值可以操作:下标,字典的key,value shop=[{'name':'hafo','price':12}, {'name':'linke','price':10}, {'name':'jili','price':8}, {'name':'dongfeng','price':5} ] e = enumerate(shop) # 使用for循环可查看下标和对应值 for i,d in e: print (i,d)返回:
(0, {'price': 12, 'name': 'hafo'})
(1, {'price': 10, 'name': 'linke'})
(2, {'price': 8, 'name': 'jili'})
(3, {'price': 5, 'name': 'dongfeng'})
如果要访问列表中的字典的key或者value,不需要使用enumerate,直接在列表中访问
shop=[{'name':'hafo','price':12}, {'name':'linke','price':10}, {'name':'jili','price':8}, {'name':'dongfeng','price':5} ] print(shop[0]['price']) print(shop[0]['name'])返回:12
hafo