zoukankan      html  css  js  c++  java
  • 笨方法学python(本文为阅读时从此书摘录的笔记) 第五天

    36.

    37.

    38.

    39.

    40.

    字典和列表的不同在于,它的索引可以是任意类型的

    >>> haha={'a':1,'b':2,'c':3}
    >>> print(haha['a'])
    1
    >>> print(haha['b'])
    2
    >>> print(haha['c'])
    3
    >>> haha['d']=4  #在字典中添加元素
    >>> print(haha['d'])
    4
    >>> print(haha)  #输出字典
    {'b': 2, 'c': 3, 'd': 4, 'a': 1}


    还有这种操作:

    >>> haha[1]='sb'
    >>> haha[2]='SB'
    >>> print(haha)
    {1: 'sb', 2: 'SB', 'c': 3, 'b': 2, 'd': 4, 'a': 1}


    删除字典中的元素:关键字del


    >>> print(haha)
    {1: 'sb', 2: 'SB', 'c': 3, 'b': 2, 'd': 4, 'a': 1}
    >>> del haha['a']
    >>> print(haha)
    {1: 'sb', 2: 'SB', 'c': 3, 'b': 2, 'd': 4}
    >>> del haha[1]
    >>> print(haha)
    {2: 'SB', 'c': 3, 'b': 2, 'd': 4}


    这是一个重要的例题

    cities = {'CA': 'San Francisco', 'MI': 'Detroit','FL': 'Jacksonville'}
    cities['NY'] = 'New York'
    cities['OR'] = 'Portland'
    
    def find_city(themap, state):
        if state in themap:  #看最后的例子
            return themap[state]
        else:
            return "Not found."
    
    cities['_find'] = find_city  #这里把函数名当做变量,如果这句写在函数之前就会报错
    
    while True:
        print "State? (ENTER to quit)",
        state = raw_input("> ")
    
        if not state: break   #当没有录入时state为''或者None此时not state为True
    
        city_found = cities['_find'](cities, state)
        print city_found
    >>> not ''
    True
    >>> not 123
    False
    >>> not'12'
    False
    >>> not None
    True


    >>> haha={'a':1,'b':2,'c':3}
    >>> 'a' in haha
    True

  • 相关阅读:
    ab命令做压测测试
    用js两张图片合并成一张图片
    Web全景图的原理及实现
    深入理解Java中的IO
    Spring AOP详解
    spring @Transactional注解参数详解
    优化MyBatis配置文件中的配置
    使用MyBatis对表执行CRUD操作
    @requestBody注解的使用
    url 拼接的一个模块furl
  • 原文地址:https://www.cnblogs.com/iamjuruo/p/7470918.html
Copyright © 2011-2022 走看看