zoukankan      html  css  js  c++  java
  • Dictionaries and tuples

    Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair. As you should expect from a dictionary, the items are in no particular order. Conversely, you can use a list of tuples to initialize a new dictionary:

                           

    Combining this feature with zip yields a concise way to create a dictionary:

     

    The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to an existing dictionary.

     

    Combining items, tuples assignment and for, you get the idiom for traversing the keys and values of a dictionary:

     

    It is common to use tuples as keys in dictionaries (primary because you can’t use lists). For examples, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:

    directory[last,first] = number

    The expression in brackets is a tuple. We could use tuple assignment to traverse this dictionary.

    for last, first in directory:
              print first, last, directory[last,first]

    This loop traverse the keys in directory, which are tuples. It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number. There are two ways to represent tuples in a state diagram. The more detailed version shows the indices and elements just as they appear in a list. For example, the tuple (‘Cleese’, ‘John’) would appear:

     

    But in a larger diagram you might want to leave out the details. For example, a diagram of the telephone directory might appear:

     

    Here the tuples are shown using Python syntax as a graphical shorthand.

    from Thinking in Python

  • 相关阅读:
    7387. 【2021.11.16NOIP提高组联考】数析送命题
    js 数组的基本操作
    界面跳转已打开界面强制刷新
    Topshelf安装Windows服务
    np_utils.to_categorical
    SQLServer数据库的.ldf文件太大怎办?
    Maven报错Please ensure you are using JDK 1.4 or above and not a JRE解决方法!
    [学习笔记]设计模式之Factory Method
    [学习笔记]设计模式之Singleton
    [学习笔记]设计模式之Abstract Factory
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/3855393.html
Copyright © 2011-2022 走看看