zoukankan      html  css  js  c++  java
  • python 字典 注意点

    dict()构造函数直接从键-值对序列创建字典:

    >>>
    >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    {'sape': 4139, 'jack': 4098, 'guido': 4127}


    此外,字典推导式式可以用于从任意键和值表达式创建字典:

    >>>
    >>> {x: x**2 for x in (2, 4, 6)}
    {2: 4, 4: 16, 6: 36}


    如果键都是简单的字符串,

    有时通过关键字参数指定 键-值 对更为方便:

    >>>
    >>> dict(sape=4139, guido=4127, jack=4098)
    {'sape': 4139, 'jack': 4098, 'guido': 4127}


    2.遍历技巧
    使用enumerate(list)可以同时检索到序列的key和对应的value
    for i,value in enumerate(list):
      XXXX

    对字典使用iteritems()同时取得键和对应的值。

    同时遍历两个或更多的序列,

    使用zip()函数可以成对读取元素。

    >>>
    >>> questions = ['name', 'quest', 'favorite color']
    >>> answers = ['lancelot', 'the holy grail', 'blue']
    >>> for q, a in zip(questions, answers):
    ...     print 'What is your {0}?  It is {1}.'.format(q, a)

    要反向遍历一个序列,

    首先正向生成这个序列,

    然后调用 reversed() 函数。

    >>>
    >>> for i in reversed(xrange(1,10,2)):
    ...     print i
     

    循环一个序列按排序顺序,

    请使用sorted()函数,

    返回一个新的排序的列表,

    同时保留源不变。

    >>>
    >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    >>> for f in sorted(set(basket)):
    ...     print f
     

    若要在循环内部修改正在遍历的序列(例如复制某些元素),

    建议您首先制作副本。

    在序列上循环不会隐式地创建副本。

    切片表示法使这尤其方便:

    >>>
    >>> words = ['cat', 'window', 'defenestrate']
    >>> for w in words[:]:  # Loop over a slice copy of the entire list.
    ...     if len(w) > 6:
    ...         words.insert(0, w)
    ...
    >>> words
    ['defenestrate', 'cat', 'window', 'defenestrate']
     
  • 相关阅读:
    Oracle 多版本控制
    texedo 分布式事务
    OLAP 大表和小表并行hash join
    分页SQL模板
    全表扫描分页
    索引的结构图
    利用函数索引优化<>
    分页SQL取下一页
    SORT ORDER BY STOPKEY
    压缩跟踪(CT)代码具体学习_模块1(样本的採集和扩充)
  • 原文地址:https://www.cnblogs.com/hackerl/p/4783849.html
Copyright © 2011-2022 走看看