zoukankan      html  css  js  c++  java
  • python 数据类型 --- 集合

    1. 注意列表和集合的区别 set

    列表表现形式: list_1 = [1,3,4];  集合表现形式:set_1= set()

    list_1 = [1,2,3,4,23,4,2]
    print(list_1,type(list_1))
    list_1 = set(list_1)
    print(list_1,type(list_1))
    list_2 = set([2,4,6,8,10])
    print(list_2,type(list_2))
    
    #运行结果
    [1, 2, 3, 4, 23, 4, 2] <class 'list'>
    {1, 2, 3, 4, 23} <class 'set'>
    {8, 2, 10, 4, 6} <class 'set'>

    2. 集合的关系:

    ############################# 集合的关系测试 part ###################################
    #交集
    print(list_1.intersection(list_2))
    #对称差集  除去两个集合的交集的那部分
    print(list_1.symmetric_difference(list_2))
    #并集
    print(list_1.union(list_2))
    #差集
    # is in list_1 , but not in list_2
    print(list_1.difference(list_2))
    # is in list_2, but not in list_1
    print(list_2.difference(list_1))
    #子集
    list_3 = set([6,8,10])
    print(list_3.issubset(list_2))
    #父集
    print(list_2.issuperset(list_3))
    #""" Return True if two sets have a null intersection. """
    print(list_1.isdisjoint(list_3))
    print(list_1.isdisjoint(list_2))
    '''

     "&  |  - ^ " 集合关系的另一种表示方法

    #交集
    print("交集->", list_1 & list_2)
    #union
    print("并集->", list_1 | list_2)
    # difference
    print("difference-->",list_1 - list_2)  # is in list_1 but not in list_2
    #对称差集
    print("对称差集-->", list_1 ^ list_2)

    3. 集合的方法 add , update , remove, len, in , not in , pop, discard

    list_1 = (1,3,5,7)
    list_2 = ([1,3,5,7])
    list_3 = set([1,3,5,7])
    print(list_1,type(list_1))
    print(list_2,type(list_2))
    print(list_3,type(list_3))
    #1.添加一项 add, 添加多项update
    list_3.add(9)
    print("test1--",list_3)
    list_3.update([11,13])
    print("test2--",list_3)
    # 2.移走一项
    list_3.remove(11)
    print("test3--",list_3)
    #.3 长度
    print("test4--",len(list_3))
    # 4.在不在里面
    print("test5---", 6 in list_3, 3 in list_3, 11 not in list_3)
    # 5.删除任意的set element ,并返回
    print(list_3.pop())
    list_3.discard() # Remove an element from a set if it is a member.If the element is not a member, do nothing.
    
    list_3.remove() #Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError
  • 相关阅读:
    原!!如何将多个复杂查询整合成一个查询,并作为一个对象的各个字段输出
    转!!mysql order by 中文排序
    mybatis 模糊查询 like
    转!!log4j基础
    CI框架下的PHP增删改查总结
    tp5中url使用js变量传参方法
    一个用户管理的ci框架的小demo--转载
    CI框架入门教程
    PHP的CI框架流程基本熟悉
    CI
  • 原文地址:https://www.cnblogs.com/frankb/p/6204666.html
Copyright © 2011-2022 走看看