zoukankan      html  css  js  c++  java
  • python循环技巧

    在字典中循环时,关键字和对应的值可以使用 items() 方法同时解读出来

    >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    >>> for k, v in knights.items():
    ...     print k, v
    ...
    gallahad the pure
    robin the brave
    字典的格式以{key:value}的格式来定义
    比如
    a = {'name':'xiaoming','age':23}
    字典支持嵌套

    下面介绍的操作方法用到的例子是:
    a = {'name':'xiaoming','age':23}

    Python的字典的items(), keys(), values()都返回一个list

    >>> dict = { 1 : 2, 'a' : 'b', 'hello' : 'world' }
    >>> dict.values()
    ['b', 2, 'world']
    >>> dict.keys()
    ['a', 1, 'hello']
    >>> dict.items()
    [('a', 'b'), (1, 2), ('hello', 'world')]
    >>>

    遍历字典的几种方法:

    #!/usr/bin/python 
    dict={"a":"apple","b":"banana","o":"orange"} 
     
    print "##########dict######################" 
    for i in dict: 
            print "dict[%s]=" % i,dict[i] 
     
    print "###########items#####################" 
    for (k,v) in  dict.items(): 
            print "dict[%s]=" % k,v 
     
    print "###########iteritems#################" 
    for k,v in dict.iteritems(): 
            print "dict[%s]=" % k,v 
     
    print "###########iterkeys,itervalues#######" 
    for k,v in zip(dict.iterkeys(),dict.itervalues()): 
            print "dict[%s]=" % k,v 
     

    序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到

     
    >>> for i, v in enumerate(['tic', 'tac', 'toe']):
    ...     print i, v
    ...
    0 tic
    1 tac
    2 toe

    同时循环两个或更多的序列,可以使用 zip() 整体解读。

    >>> questions = ['name', 'quest', 'favorite color']
    >>> answers = ['lancelot', 'the holy grail', 'blue']
    >>> for q, a in zip(questions, answers):
    ...     print 'What is your %s?  It is %s.' % (q, a)
    ...     
    What is your name?  It is lancelot.
    What is your quest?  It is the holy grail.
    What is your favorite color?  It is blue.
  • 相关阅读:
    python 文件和路径操作函数小结
    python文件处理
    jquery操作select
    ubuntu 安装ODOO时的python的依赖
    XML-RPC 实现C++和C#交互
    C#接收xmlrpc接口返回哈希表格式
    XmlRpc with C#/Java【转】
    OpenERP 的XML-RPC的轻度体验+many2many,one2many,many2one创建方式
    在Ubuntu Server上源码安装OpenERP 8.0,并配置wsgi和nginx运行环境
    C# 文件与二进制互转数据库写入读出
  • 原文地址:https://www.cnblogs.com/youxin/p/3059931.html
Copyright © 2011-2022 走看看