zoukankan      html  css  js  c++  java
  • Python3中enumerate的使用

    用法:对于一个可迭代的(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)
  • 相关阅读:
    dispatch_semaphore
    dispatch_set_target_queue
    iOS charles支持https抓包
    ios8 毛玻璃效果
    工程里配置.xconfig文件
    线程安全的nsmutabledictionary(读weex代码)
    关于信号量以及多线程的代码
    dispatch_set_target_queue测试
    dyld: Library not loaded问题解决
    iOS图片上加标签或者水印
  • 原文地址:https://www.cnblogs.com/gepu1991/p/9108396.html
Copyright © 2011-2022 走看看