• 序列使用enumerate()的例子 分类: python 20121205 13:06 193人阅读 评论(0) 收藏


    #! /usr/bin/env python

    #coding=utf-8


    a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]

    #每行显示6个列表元素
    for i,v in enumerate(a):
        if i!=0 and i%6==0:
            print
        print v,


    #列表中使用enumerate()
    print '*'*20+'List enumerate()'+'*'*20
    a=[1,'abc',3,'I am a boy',2.34,-9]
    for i,v in enumerate(a):
        print 'The %d element in list is:%s' %(i,v), \
         '  '*2+'Type:',type(v),'\n'#取得列表数据的类型,换行



    #字符串中使用enumerate()
    print '*'*20+'String enumerate()'+'*'*20
    b='1ab34cd'
    for i,v in enumerate(b):
        print 'The %d element in list is:%s' %(i,v), \
         '  '*2+'Type:',type(v),'\n'#取得列表数据的类型,换行



    #元组中使用enumerate()
    print '*'*20+'Tuple enumerate()'+'*'*20
    c=(1,'abc',2.3,'5.6','I am a boy')

    for i,v in enumerate(c):
        print 'The %d element in list is:%s' %(i,v), \

         '  '*2+'Type:',type(v),'\n'#取得列表数据的类型,换行



    结果:



    ********************List enumerate()********************
    The 0 element in list is:1     Type: <type 'int'>

    The 1 element in list is:abc     Type: <type 'str'>

    The 2 element in list is:3     Type: <type 'int'>

    The 3 element in list is:I am a boy     Type: <type 'str'>

    The 4 element in list is:2.34     Type: <type 'float'>

    The 5 element in list is:-9     Type: <type 'int'>

    ********************String enumerate()********************
    The 0 element in list is:1     Type: <type 'str'>

    The 1 element in list is:a     Type: <type 'str'>

    The 2 element in list is:b     Type: <type 'str'>

    The 3 element in list is:3     Type: <type 'str'>

    The 4 element in list is:4     Type: <type 'str'>

    The 5 element in list is:c     Type: <type 'str'>

    The 6 element in list is:d     Type: <type 'str'>

    ********************Tuple enumerate()********************
    The 0 element in list is:1     Type: <type 'int'>

    The 1 element in list is:abc     Type: <type 'str'>

    The 2 element in list is:2.3     Type: <type 'float'>

    The 3 element in list is:5.6     Type: <type 'str'>

    The 4 element in list is:I am a boy     Type: <type 'str'>



    l=range(10)
    #方法一
    for i in l:
        print i,
        if i!=0 and i%5==0:
            print

    print

    #方法二
    for m in l:
        if m!=0 and m%6==0:
            print
        print m,


    有一个list = ["a","b","c","d"],想要转化成一个dict = ["1":"a","2":"b","3":"c","4":"d"]

    dict([str(i+1),j for i,j in enumerate(list)])



    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    无法定位程序输入点 ucrtbase.terminate 于动态链接库 api-ms-win-crt-runtime-|1-1-0.dll 上的解决方案
    .net 使用语音播放文字
    Firebird 数据库使用经验总结
    firebird 中的域
    WPF 中 OpenClipboard 失败问题
    Delphi Format 格式化数字
    画圆弧方法
    java.util.concurrent
    linux下软件安装方法
    基于java的http服务器
  • 原文地址:https://www.cnblogs.com/think1988/p/4628267.html
Copyright © 2020-2023  润新知