当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3中enumerate的使用

Python3中enumerate的使用

2018年05月30日  | 移动技术网IT编程  | 我要评论

海淀区工人文化宫,绝品天医无弹窗,消化不良怎么办

用法:对于一个可迭代的(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)

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网