• python的字典和集合


    https://www.cnblogs.com/kingofkai/p/5901494.html

    字典(dist)--类似java的map

    写法:

    写法一:
    >>>empty = {}
    >>>empty
    {}
    >>>type(empty)
    <class 'dict'>
    
    写法二,使用dict()来创建字典:
    >>>dict1 = dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
    >>>dict1
    {'s':115,'C',67,'F':70,'h':104,'i':105}

    写法三(注意键位置的字符串不能加字符串的引号):
    >>>dict1 = dict(F=70,i=105,s=115,h=104,C=67)
    >>>dict1
    {'C':67,'s':115,'F':70,'h':104,'i':105}

    写法四:
    >>>dict1
    {'C':67,'s':115,'F':70,'h':104,'i':105}
    >>>dict1['x'] = 88
    >>>dict1
    {'C': 67, 's': 115, 'F': 70, 'h': 104, 'i': 105, 'x': 88}
    >>>dict1['x'] = 120
    >>>dict1
    {'C': 67, 's': 115, 'F': 70, 'h': 104, 'i': 105, 'x': 120}

     dict的内置函数:

    1、fromkeys()
    2、keys()、values()和items()
    3get()
    4、copy()
    5、pop()和popitem()
    6、update()

     集合(set)---类似java的set

    >>>num1 = {}
    >>>type(num1)
    <class 'dict'>
    
    >>>num2 = {1,2,3,4}
    >>>type(num2)
    <class 'set'>
    
    >>>num = {1,2,3,4,5,4,3,2}
    >>>num
    {1,2,3,4,5}
    
    #由此可见,python和java的set一样,都是不可重复的
    #而且也是无序的

    创建集合

    方法一:把元素直接用大括号括起来{}
    
    >>>set1 = {"song","cui","ting"}
    
    
    方法二:使用set()
    >>>set2 = set(["song""cui","ting"])

    访问集合

    >>>set1 = {1,2,3,4,5,4,3,2,1,0}
    >>>for each in set1
                print(each,end='')
    0 1 2 3 4 5
    
    >>>o in set1
    True
    >>>'XX' not in set1
    True
    
    >>>set1.add(6)
    {0,1,2,3,4,5,6}
    >>>set1.remove(5)
    >>>set1
    {0,1,2,3,4,6}

    不可变集合

    有时候喜欢set的数据具有稳定性,如元组一样,不能随意增加或者删除集合中的元素。我们可以用forzenset()函数来定义不可变集合。就是把set元素给frozen(冰冻)起来

    >>>set1 = frozenset({1,2,3,4,5})
    >>>set1.add(6)
    
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        set1.add(6)
    AttributeError: 'frozenset' object has no attribute 'add'
    

      

  • 相关阅读:
    ibatis $与#的区别
    (转载)Hibernate与Jpa的关系
    tomcat web工程 jar包冲突解决方法
    jquery 获取checkbox 选中值并拼接字符集
    mysql BLOB字段转String的方法
    Ajax工作原理
    Spring mvc 具体RequestMapping 参数含义
    覆盖bootstrap的样式
    开园啦,致曾经现在以后的自己~
    SimpleDateFormat 常规用法
  • 原文地址:https://www.cnblogs.com/songcuiting/p/11208916.html
Copyright © 2020-2023  润新知