zoukankan      html  css  js  c++  java
  • Looping Techniques

    When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

    >>>
    >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    >>> for k, v in knights.items():
    ...     print(k, v)
    ...
    gallahad the pure
    robin the brave
    

    When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

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

    To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

    >>>
    >>> 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))
    ...
    What is your name?  It is lancelot.
    What is your quest?  It is the holy grail.
    What is your favorite color?  It is blue.
    

    To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

    >>>
    >>> for i in reversed(range(1, 10, 2)):
    ...     print(i)
    ...
    9
    7
    5
    3
    1
    

    To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

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

    To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

    >>>
    >>> 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']
  • 相关阅读:
    几款开源的图形界面库(GUI Libraries)
    CMenu菜单
    开源免费的C/C++网络库(c/c++ sockets library) 七剑下天山
    基于MFC的ActiveX控件开发
    VC++中动态生成菜单技巧
    ActiveX控件打包成Cab置于网页中自动下载安装
    VC++API小查
    全面解析MFC应用程序中处理消息的顺序
    CMenu类的使用方法
    跨域单点登录实现(使用iframe)_勇敢的心_百度空间
  • 原文地址:https://www.cnblogs.com/dltts/p/5984086.html
Copyright © 2011-2022 走看看