• python入门_老男孩_集合_元祖


     集合  可变数据类型,内置元素必须是不可变类型,无序,不重复

      增

        set.add

        set.update

      

        del

        pop

        remove

        clear

      查

        for

        切片

    # 集合
    # 创建
    set1 = set({1,2,3})
    # 集合内置元素必须是不可变类型
    # set2 = set({1,[2,3],{'name':larry}}) false
    
    #
    set1.add('小赵女神')
    print(set1)
    
    set1.update('love')
    print(set1)
    
    #
    set1.pop() # 随机删除
    print(set1.pop()) # 有返回值
    print(set1)
    
    set1.remove('l') # 按元素删除
    print(set1)
    
    set1.clear() # 清空集合
    print(set1) # 返回set()
    
    # del set1    # 删除集合
    # print(set1)
    
    #
    set1 = set({1,2,3})
    for i in set1:
        print(i,type(i))
    
    # print(set1[0]) # 不支持索引
    # print(set1[0:3] # 不支持切片
    View Code

      运算

        intersection

        union

        difference

        issubset

        issuperset

    # 运算操作
    # 交集
    set2 = {1,2,3,4,5}
    set3= {3,4,5,6,7,8}
    
    set4 = set2 & set3 
    set5 = set2.intersection(set3)
    
    print(set4, set5)
    # 并集
    set6 = set2 | set3
    set7 = set2.union(set3)
    
    print(set6, set7)
    # 差集
    set8 = set2 - set3
    set9 = set2.difference(set3)
    
    print(set8, set9)
    # 子集
    set3 = {1,2,3}
    set4 = {1,2,3,4,5,6}
    
    print(set3 < set4)
    print(set3.issubset(set4))
    
    print(set4 > set3)
    View Code

      去重小案例

    # 列表去重的两种方法
    # 方法一,转换成集合
    li = [1,3,3,44,5,33,44]
    temp = set(li)
    li = list(temp)
    print(li)
    
    # 方法二,for循环
    li = ['a', 'b', 'c', 'a']
    l = []
    for i in li:
        for i not in l:
            l.append(i)
    print(l)
    View Code

    元祖

      创建

    >>>tup1 = ('Google', 'Runoob', 1997, 2000);
    >>> tup2 = (1, 2, 3, 4, 5 );
    >>> tup3 = "a", "b", "c", "d";   #  不需要括号也可以
    >>> type(tup3)
    <class 'tuple'>
    View Code

      类型

    >>>tup1 = (50)
    >>> type(tup1)     # 不加逗号,类型为整型
    <class 'int'>
     
    >>> tup1 = (50,)
    >>> type(tup1)     # 加上逗号,类型为元组
    <class 'tuple'>
    View Code

      查

    tup1 = ('Google', 'Runoob', 1997, 2000)
    tup2 = (1, 2, 3, 4, 5, 6, 7 )
     
    print ("tup1[0]: ", tup1[0])
    print ("tup2[1:5]: ", tup2[1:5])
    View Code

      拼接

    tup1 = (12, 34.56);
    tup2 = ('abc', 'xyz')
     
    # 以下修改元组元素操作是非法的。
    # tup1[0] = 100
     
    # 创建一个新的元组
    tup3 = tup1 + tup2;
    print (tup3)
    View Code

  • 相关阅读:
    开源项目
    [Accessibility] Missing contentDescription attribute on image [可取行]失踪contentDescription属性图像
    Android 布局 中实现适应屏幕大小及组件滚动
    EF 错误记录
    EasyUI 加载时需要显示和隐藏 panel(面板)内容破版问题
    IE 报表缩放后页面破版
    VS 2017 引入nuget 问题
    SSRS 报表显示页面 asp net session丢失或者找不到 asp net session has expired or could not be found()
    log4net 配置
    网站
  • 原文地址:https://www.cnblogs.com/dignity/p/9754737.html
Copyright © 2020-2023  润新知