• Python学习笔记——集合


    1. 定义

    num = {}
    print(type(num))
    num2 = {1,2,3,4,5}
    print(type(num2))
    
    <class 'dict'>
    <class 'set'>
    

    集合的数据是唯一的

    # 会自动去除重复数据
    num2 = {1,2,3,4,5,5,3,2}
    print(num2)
    
    {1, 2, 3, 4, 5}
    

    集合的数据是无序的

    # 以下表达会报错
    num2[2]
    
    ---------------------------------------------------------------------------
    
    TypeError                                 Traceback (most recent call last)
    
    <ipython-input-4-87e68eb3c3c4> in <module>()
    ----> 1 num2[2]
    
    TypeError: 'set' object does not support indexing
    

    2. set()

    # set函数可以传进一个列表、元组、字符串
    set1 = set([1,2,3,4,5,5])
    print(set1)
    
    {1, 2, 3, 4, 5}
    

    去除列表[0,1,2,3,4,5,5,3,1]中重复的元素

    # 利用for循环
    num3 = [1,2,3,4,5,5,3,1,0]
    temp = []
    for each in num3:
        if each not in temp:
            temp.append(each)
    print(temp)
    
    [1, 2, 3, 4, 5, 0]
    
    # 利用set函数,但是要注意,使用set可能会改变元素在集合中的位置,如num3中的0
    num3 = list(set(num3))
    print(num3)
    
    [0, 1, 2, 3, 4, 5]
    

    3. 集合的相关操作

    # in 和 not in
    print(6 in set1)
    print(6 not in set1)
    
    False
    True
    
    # add() 和 remove()
    set2 = set([1,2,3,4,5,5])
    set2.add(6)
    print(set2)
    set2.remove(5)
    print(set2)
    
    {1, 2, 3, 4, 5, 6}
    {1, 2, 3, 4, 6}
    

    4. frozenset

    # 定义一个不可变的集合,此时集合不可更改,否则会报错
    set3 = frozenset([1,2,3,4,5])
    set3.add(0)
    
    ---------------------------------------------------------------------------
    
    AttributeError                            Traceback (most recent call last)
    
    <ipython-input-32-d6bbd56c6855> in <module>()
          1 # 定义一个不可变的集合
          2 set3 = frozenset([1,2,3,4,5])
    ----> 3 set3.add(0)
    
    AttributeError: 'frozenset' object has no attribute 'add'
    
  • 相关阅读:
    LocalDB数据库修改排序规则,修复汉字变问号
    设计模式读书笔记-单件模式(创建型模式)
    supersocket实现上传文件
    一步一步架起MyBatis
    windows平台下cmake+gtest工程调试
    嵌入式Linux模块移植四部曲
    一次惊呆的调试经历
    阅读《大型网站技术架构》第五章、第六章心得
    阅读《大型网站技术架构》第四章心得
    阅读《大型网站技术架构》 第三章心得
  • 原文地址:https://www.cnblogs.com/nigream/p/11251126.html
Copyright © 2020-2023  润新知