python全栈开发day12

列表

创建列表:
基本操作:
  • 索引

  • 切片

  • 追加

  • 删除

  • 长度

  • 切片

  • 循环

      • 包含

         1 #######################列表list类中提供的方法########################
         2 list2 = [ 'x','y','i','o','i','a','o','u','i']
         3 # 1、append() 在列表后面追加元素
         4 list1 = ['Google', 'Runoob', 'Taobao']
         5 list1.append(123)
         6 print (list1)
         7 list2.append('xiong')
         8 print(list2)
         9 # 2、clear() 清空列表
        10 list3 = [1,2,3,4,5]
        11 list3.clear()
        12 print(list3)
        13 # 3、copy() 浅拷贝
        14 list4 = list3.copy()
        15 print(list4)
        16 # 4、计算元素11出现的次数
        17 print(list2.count('i'))
        18 # 5、extend(iterable)  传入可迭代对象(将可迭代对象一个个加入到列表中) 扩展列表
        19 list1 = ['xjt','xd','xe']
        20 list2 = [11,22,'xiong','zhang','zhou',True,22]
        21 list2.extend(list1)
        22 print(list2)     #--->[11, 22, 'xiong', 'zhang', 'zhou', True,22, 'xjt', 'xd', 'xe']
        23 # 6、index() 根据值获取索引位置 找到停止,左边优先
        24 print(list2.index(22))      #默认从0位置开始找
        25 print(list2.index(22,3))  #从第3个位置找22
        26 # 7、pop() 在指定索引位置插入元素
        27 list0 = [11,22,33]
        28 list0.insert(1,'xiong')
        29 print(list0)
        30 # 8、pop() 默认把列表最后一个值弹出 并且能获取弹出的值
        31 list0 = [11,22,33,'xiong',90]
        32 list0.pop()
        33 print(list0)
        34 list0.pop(2)
        35 print(list0)
        36 # 9、reversed() 将当前列表进行翻转
        37 list0 = [11,22,33,'xiong',90]
        38 list0.reverse()
        39 print(list0)
        40 # 10、sort() 排序,默认从小到大
        41 list1 = [11,22,55,33,44,2,99,10]
        42 list1.sort()   #从小到大
        43 print(list1)
        44 list1.sort(reverse=True)   #从大到小
        45 print(list1)
          1 class list(object):
          2     """
          3     list() -> new empty list
          4     list(iterable) -> new list initialized from iterable's items
          5     """
          6     def append(self, p_object): # real signature unknown; restored from __doc__
          7         """ L.append(object) -- append object to end """
          8         pass
          9 
         10     def count(self, value): # real signature unknown; restored from __doc__
         11         """ L.count(value) -> integer -- return number of occurrences of value """
         12         return 0
         13 
         14     def extend(self, iterable): # real signature unknown; restored from __doc__
         15         """ L.extend(iterable) -- extend list by appending elements from the iterable """
         16         pass
         17 
         18     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
         19         """
         20         L.index(value, [start, [stop]]) -> integer -- return first index of value.
         21         Raises ValueError if the value is not present.
         22         """
         23         return 0
         24 
         25     def insert(self, index, p_object): # real signature unknown; restored from __doc__
         26         """ L.insert(index, object) -- insert object before index """
         27         pass
         28 
         29     def pop(self, index=None): # real signature unknown; restored from __doc__
         30         """
         31         L.pop([index]) -> item -- remove and return item at index (default last).
         32         Raises IndexError if list is empty or index is out of range.
         33         """
         34         pass
         35 
         36     def remove(self, value): # real signature unknown; restored from __doc__
         37         """
         38         L.remove(value) -- remove first occurrence of value.
         39         Raises ValueError if the value is not present.
         40         """
         41         pass
         42 
         43     def reverse(self): # real signature unknown; restored from __doc__
         44         """ L.reverse() -- reverse *IN PLACE* """
         45         pass
         46 
         47     def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
         48         """
         49         L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
         50         cmp(x, y) -> -1, 0, 1
         51         """
         52         pass
         53 
         54     def __add__(self, y): # real signature unknown; restored from __doc__
         55         """ x.__add__(y) <==> x+y """
         56         pass
         57 
         58     def __contains__(self, y): # real signature unknown; restored from __doc__
         59         """ x.__contains__(y) <==> y in x """
         60         pass
         61 
         62     def __delitem__(self, y): # real signature unknown; restored from __doc__
         63         """ x.__delitem__(y) <==> del x[y] """
         64         pass
         65 
         66     def __delslice__(self, i, j): # real signature unknown; restored from __doc__
         67         """
         68         x.__delslice__(i, j) <==> del x[i:j]
         69                    
         70                    Use of negative indices is not supported.
         71         """
         72         pass
         73 
         74     def __eq__(self, y): # real signature unknown; restored from __doc__
         75         """ x.__eq__(y) <==> x==y """
         76         pass
         77 
         78     def __getattribute__(self, name): # real signature unknown; restored from __doc__
         79         """ x.__getattribute__('name') <==> x.name """
         80         pass
         81 
         82     def __getitem__(self, y): # real signature unknown; restored from __doc__
         83         """ x.__getitem__(y) <==> x[y] """
         84         pass
         85 
         86     def __getslice__(self, i, j): # real signature unknown; restored from __doc__
         87         """
         88         x.__getslice__(i, j) <==> x[i:j]
         89                    
         90                    Use of negative indices is not supported.
         91         """
         92         pass
         93 
         94     def __ge__(self, y): # real signature unknown; restored from __doc__
         95         """ x.__ge__(y) <==> x>=y """
         96         pass
         97 
         98     def __gt__(self, y): # real signature unknown; restored from __doc__
         99         """ x.__gt__(y) <==> x>y """
        100         pass
        101 
        102     def __iadd__(self, y): # real signature unknown; restored from __doc__
        103         """ x.__iadd__(y) <==> x+=y """
        104         pass
        105 
        106     def __imul__(self, y): # real signature unknown; restored from __doc__
        107         """ x.__imul__(y) <==> x*=y """
        108         pass
        109 
        110     def __init__(self, seq=()): # known special case of list.__init__
        111         """
        112         list() -> new empty list
        113         list(iterable) -> new list initialized from iterable's items
        114         # (copied from class doc)
        115         """
        116         pass
        117 
        118     def __iter__(self): # real signature unknown; restored from __doc__
        119         """ x.__iter__() <==> iter(x) """
        120         pass
        121 
        122     def __len__(self): # real signature unknown; restored from __doc__
        123         """ x.__len__() <==> len(x) """
        124         pass
        125 
        126     def __le__(self, y): # real signature unknown; restored from __doc__
        127         """ x.__le__(y) <==> x<=y """
        128         pass
        129 
        130     def __lt__(self, y): # real signature unknown; restored from __doc__
        131         """ x.__lt__(y) <==> x<y """
        132         pass
        133 
        134     def __mul__(self, n): # real signature unknown; restored from __doc__
        135         """ x.__mul__(n) <==> x*n """
        136         pass
        137 
        138     @staticmethod # known case of __new__
        139     def __new__(S, *more): # real signature unknown; restored from __doc__
        140         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        141         pass
        142 
        143     def __ne__(self, y): # real signature unknown; restored from __doc__
        144         """ x.__ne__(y) <==> x!=y """
        145         pass
        146 
        147     def __repr__(self): # real signature unknown; restored from __doc__
        148         """ x.__repr__() <==> repr(x) """
        149         pass
        150 
        151     def __reversed__(self): # real signature unknown; restored from __doc__
        152         """ L.__reversed__() -- return a reverse iterator over the list """
        153         pass
        154 
        155     def __rmul__(self, n): # real signature unknown; restored from __doc__
        156         """ x.__rmul__(n) <==> n*x """
        157         pass
        158 
        159     def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        160         """ x.__setitem__(i, y) <==> x[i]=y """
        161         pass
        162 
        163     def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        164         """
        165         x.__setslice__(i, j, y) <==> x[i:j]=y
        166                    
        167                    Use  of negative indices is not supported.
        168         """
        169         pass
        170 
        171     def __sizeof__(self): # real signature unknown; restored from __doc__
        172         """ L.__sizeof__() -- size of L in memory, in bytes """
        173         pass
        174 
        175     __hash__ = None
        View Code
        元祖
        创建元祖:
        1
        2
        3
        ages = (1122334455)
        ages = tuple((1122334455))
        ##区别元组与函数的参数括号:元组创建时在最后面多加一个逗号,   函数参数括号中多加一个逗号会报错
        基本操作:
        • 索引
        1. tu = (111,222,'alex',[(33,44)],56)
        2. v = tu[2]
        • 切片
        1. v = tu[0:2]
        • 循环

        for item in tu:

          print(item)    

        • 长度
        • 包含
           1 ######tuple元组########
           2 #元组 元素不能别修改 不能增加 删除
           3 s = 'adfgadhs12a465ghh'
           4 li = ['alex','xiong',123,'xiaoming']
           5 tu = ("wang","zhou","zhang")
           6 
           7 print(tuple(s))
           8 print(tuple(li))
           9 print(list(tu))
          10 print("_".join(tu))
          11 ##注意:当有数字时 不能join()
          12 # tu1 = [123,"xiaobai"]
          13 # print("_".join(tu1))
          14 """列表中也能扩增元组"""
          15 li.extend((11,22,33,'zhu',))
          16 print(li)
          17 """元组的一级元素不可修改 """
          18 tu = (11,22,'alex',[(1123,55,66)],'xiong',True,234)
          19 print(tu[3][0][1])
          20 print(tu[3])
          21 tu[3][0] = 567
          22 print(tu)
          23 """元组tuple的一些方法"""
          24 tu = (11,22,'alex',[(1123,55,66)],'xiong',True,234,22,23,22)
          25 print(tu.count(22))   #统计指定元素在元组中出现的次数
          26 print(tu.index(22))     #某个值的索引
          字典(无序)
          创建字典:
          1
          2
          3
          person = {"name""mr.wu"'age'18}
          person = dict({"name""mr.wu"'age'18})

          常用操作:

          • 索引
          • 新增
          • 删除
          • 键、值、键值对
          • 循环
          • 长度
             1 ######dict静态方法##########
             2 # @staticmethod # known case
             3     def fromkeys(*args, **kwargs): # real signature unknown
             4         """ Returns a new dict with keys from iterable and values equal to value. """
             5         pass
             6 
             7     def get(self, k, d=None): # real signature unknown; restored from __doc__
             8         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
             9         pass
            10 
            11     def items(self): # real signature unknown; restored from __doc__
            12         """ D.items() -> a set-like object providing a view on D's items """
            13         pass
            14 
            15     def keys(self): # real signature unknown; restored from __doc__
            16         """ D.keys() -> a set-like object providing a view on D's keys """
            17         pass
            18 
            19     def pop(self, k, d=None): # real signature unknown; restored from __doc__
            20         """
            21         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
            22         If key is not found, d is returned if given, otherwise KeyError is raised
            23         """
            24         pass
            25 
            26     def popitem(self): # real signature unknown; restored from __doc__
            27         """
            28         D.popitem() -> (k, v), remove and return some (key, value) pair as a
            29         2-tuple; but raise KeyError if D is empty.
            30         """
            31         pass
            32 
            33     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
            34         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
            35         pass
            36 
            37     def update(self, E=None, **F): # known special case of dict.update
            38         """
            39         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
            40         If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
            41         If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
            42         In either case, this is followed by: for k in F:  D[k] = F[k]
            43         """
            44         pass
            45 
            46     def values(self): # real signature unknown; restored from __doc__
            47         """ D.values() -> an object providing a view on D's values """
            48         pass
            View Code
              1 ##########字典#############
              2 """1、数字、字符串、列表、元组、字典都能作为字典的value,还能进行嵌套"""
              3 info1 = {
              4     "zhang":123,
              5     1:"wang",
              6     "k1":[12,34,{
              7         "kk1":12,
              8         "kk2":23
              9     }],
             10     "k2":(123,456,789,[12,{"kk3":12}]),
             11     "k3":{
             12         123:"li",
             13         "wang":[1,2,3]
             14     }
             15 }
             16 print(info1)
             17 """2、列表、字典不能作为字典的key"""
             18 info2 = {
             19     12:'sss',
             20     "k1":12334,
             21     True:"1351655",
             22     (11,22):456,
             23     # [12,34]:741,
             24     # {"k2":22,"k3":33}:852
             25 }
             26 print(info2)
             27 """3、字典无序 可以通过key索引方式找到指定元素"""
             28 info2 = {
             29     12:'sss',
             30     "k1":12334,
             31     True:"1351655",
             32     (11,22):456,
             33 }
             34 print(info2["k1"])
             35 """4、字典增删"""
             36 info2 = {
             37     12:'sss',
             38     "k1":12334,
             39     True:"1351655",
             40     (11,22):456,
             41     "k2":{
             42         "kk1":12,
             43         "kk2":"jack"
             44     }
             45 }
             46 del info2[12]
             47 del info2["k2"]["kk1"]
             48 print(info2)
             49 """5、字典for循环"""
             50 info = {
             51     12:'sss',
             52     "k1":12334,
             53     True:"1351655",
             54     (11,22):456,
             55     "k2":{
             56         "kk1":12,
             57         "kk2":"jack"
             58     }
             59 }
             60 # for循环获取keys
             61 for k in info:
             62     print(k)
             63 
             64 for k in info.keys():
             65     print(k)
             66 # for循环获取values
             67 for v in info.values():
             68     print(v)
             69 # for循环获取keys values
             70 for k,v in info.items():
             71     print(k,v)
             72 
             73 
             74 """fromkeys() 根据序列 创建字典 并指定统一的值"""
             75 v1 = dict.fromkeys(['k1',122,'10'])
             76 v2 = dict.fromkeys(['k1',122,'10'],123)
             77 print(v1,v2)
             78 """根据key获取字典值,key不存在时,可以指定默认值(None)"""
             79 info = {
             80     12:'sss',
             81     "k1":12334,
             82     True:"1351655",
             83     (11,22):456,
             84     "k2":{
             85         "kk1":12,
             86         "kk2":"jack"
             87     }
             88 }
             89 #不存在key时 指定返回404,不指定时返回None
             90 v = info.get('k1',404)
             91 print(v)
             92 v = info.get('k111',404)
             93 print(v)
             94 v = info.get('k111')
             95 print(v)
             96 """pop() popitem() 删除并获取值"""
             97 info = {
             98     12:'sss',
             99     "k1":12334,
            100     True:"1351655",
            101     (11,22):456,
            102     "k2":{
            103         "kk1":12,
            104         "kk2":"jack"
            105     }
            106 }
            107 #pop() 指定弹出key="k1" 没有k1时返回404
            108 #popitem() 随机弹出一个键值对
            109 # v = info.pop("k1",404)
            110 # print(info,v)
            111 k , v = info.popitem()
            112 print(info,k,v)
            113 """setdefault() 设置值 已存在不设置 获取当前key对应的值 ,不存在 设置 获取当前key对应的值"""
            114 info = {
            115     12:'sss',
            116     "k1":12334,
            117     True:"1351655",
            118     (11,22):456,
            119     "k2":{
            120         "kk1":12,
            121         "kk2":"jack"
            122     }
            123 }
            124 v = info.setdefault('k123','zhejiang')
            125 print(info,v)
            126 """update() 已有的覆盖 没有的添加"""
            127 info.update({"k1":1234,"k3":"宁波"})
            128 print(info)
            129 info.update(kkk1=1111,kkk2=2222,kkk3="hz")
            130 print(info)
             1 """day13作业"""
             2 list1 = [11,22,33]
             3 list2 = [22,33,44]
             4 # a、获取相同元素
             5 # b、获取不同元素
             6 for i in list1:
             7     for j in list2:
             8         if i==j:
             9             print(i)
            10 for i in list1:
            11     if i not in list2:
            12         print(i)
            13 
            14 # 9*9乘法表 ##注意print() 默认end="\n" 换行 sep = " " 默认空格
            15 for i in range(1,10):
            16     for j in range(1,i+1):
            17         print(i,"*",j,"=",i*j,"\t",end="")
            18     print("\n",end="")
            19 
            20 for i in range(1,10):
            21     str1 = ""
            22     for j in range(1,i+1):
            23         str1 += str(j) + "*" + str(i) + "=" + str(i*j) + '\t'
            24     print(str1)

             

posted @ 2018-09-29 16:40  XJT2019  阅读(169)  评论(0编辑  收藏  举报