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']
  • 相关阅读:
    逻辑指的是思维的规律和规则,是对思维过程的抽象。
    逻辑
    什么是概念,判断和推理
    逻辑思维
    console.log 用法
    console.log()的作用是什么
    vue-cli创建的项目中引入第三方库报错 'caller', 'calle', and 'arguments' properties may not be...
    element-ui中upload组件如何传递文件及其他参数
    vueThink权限配置
    vue2.0集成百度UE编辑器,上传图片报错!!!
  • 原文地址:https://www.cnblogs.com/dltts/p/5984086.html
Copyright © 2011-2022 走看看