zoukankan      html  css  js  c++  java
  • python笔记——dict和set

    学习廖雪峰python3笔记_dict和set

    dict__介绍

    • dict --> dictionary(字典)--> python内置 --> 使用键-值(key-value)存储
    • dict --> 优点 --> 无论表多大,查找速度不会变慢,但是占用大量内存,内存浪费多 --> 原因:没有使用里list使用的遍历,通过建立*
      索引或内部计算出查找值的内存地址(通过哈希Hash*算法)

    dict__操作

    • 查询和插入操作
    >>> l = {'L': 95, 'YL': 96, 'LYL': 97}
    >>> l['LYL']
    97
    >>> l['LYL'] = 17
    >>> l['LYL']
    17
    
    • 插入时key不存在报错
    >>>l = ['YLY’]
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    KeyError: 'YLY'
    
    • 避免key不存在错误
    • 方法一:通过in判断key是否存在
      >>> 'YLY' in l
      False
      
    • 方法二:通过dict提供的get方法
      >>> l.get('YLY')
      >>> l.get('YLY', -1)
      -1
      
    • 删除key
    >>>l.pop('LYL')
    97
    >>>l
    {'L': 95, 'YL': 96}
    
    • 注意:dict的key必须是不可变对象-->保证hash的正确性
    >>> key = [1, 2, 3]
    >>> l[key] = 'a list'
    Traceback (most recent call last)
        File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    

    set__介绍

    • 类似于dict-->不存储value-->key不能重复

    set__操作

    • 创建set,要提供一个list作为输入的集合
    >>> l = set([1, 2, 3])
    >>> l
    {1, 2, 3}
    
    • 重复元素在set中被自动过滤:
    >>> l = set([a, a, b, b, c, c)]
    >>> l
    {a, b, c}
    
    • 添加元素,重复添加不会有效果--add(key)
    >>> l.add(d)
    >>> l
    {a, b, c, d}
    
    • 删除元素--remove(key)
    >>> l.remove(d)
    >>> l
    {a, b, c}
    
  • 相关阅读:
    二分法查找递归方式()
    JDBC操作MySQL(crud)
    (转)JAVA中的权限修饰符
    抽象类和接口(面试题总结)
    java基础-集合
    Java泛型通配符以及限定
    div中嵌套的多个div使用了浮动后居中的办法
    将博客搬至CSDN
    (补)Java解析XML之dom4j
    Java单元测试
  • 原文地址:https://www.cnblogs.com/isChenJY/p/7616211.html
Copyright © 2011-2022 走看看