zoukankan      html  css  js  c++  java
  • 第二部分 python基础 day101112 运算符与基本数据类型

    python开发IDE:pycharm、elipse

    专业版、不要汉化(否则很多好用的功能用不了)

    一、运算符

    1、算数运算:结果为数值

    count = count + 1          count += 1

    count = count - 1          count -= 1

    count = count * 1          count *= 1

    count = count / 1          count /= 1

    2、比较运算:结果为真假(布尔型)

    not   取反:如not true = false

    3、赋值运算:结果为数值

    4、逻辑运算:结果为真假(布尔型)

    运算参数优先级:有括号先算括号的;从前往后依次计算。

    u = A and B or C and D

    (1)如果and前面的A假,A and B的结果直接输出假;如果A真看and后面的B决定A and B真假

    (2)如果or前面真,A and B or C直接输出真;如果or前为假,继续看or后面的C决定A and B or C真假

    总结:True OR =======》True

        False AND =====》False

    5、成员运算:结果为真假(布尔型)

    name = "郑建文"
    
    if "" in name:  #判断是否包含
        print('OK')
    else:
        print('error')

    多行加注释:选中多行后,ctrl+?即可

    二、基本数据类型

    1、数字    int(整型)
      在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
      在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
    #int()将字符串a转换为字符b
    a = "123"
    print(type(a),a)      #打印a的类型<class 'str'> 123
    num = int(a)         #不加base默认直接脱去引号
    print(type(num),num)    #打印num的类型<class 'int'> 123
    c = "123a"
    d = int(c)          #会报错,因为转换不了
    e = "0011"
    f = int(e,base=2)      #将e以进制转换为十进制
    e = "a"
    f = int(e,base=16)      #将e以十六进制转换为十进制,输出结果为10
    print(f)
    #bit_length()
    age = 10          #该数字的二进制至少需要几位:1,01,10,11,100,101,110,111.。。。。
    v
    = age.bit_length() print(v)
     
    Python3中数字不管多大,都是int,不存在long(长整型)。
    看介绍,按住Ctrl键,会有小手链接,打开就相当于help。此法就可以看int类型能干嘛,有哪些函数。
    2、布尔值bool
      真True或假False
      1 或 0
    3、字符串str

    7个基本魔法:join(), split(), find(), strip(), upper(), lower(),replace()

    灰魔法5个:适用于所有数据类型
    #1.索引,下标,获取字符串中某一个字符或者下标
    test =  "tjvjlxmo"
    v = test[3]    
    print(v)              #j
    
    #2. 切片
    v=test[0:3]         #左闭右开取出012
    v= test[0:-1]       #-1表示直接到字符串末尾,但是此时取不到最后一位,依旧满足左闭右开;负几就代表倒着数几个
                 
    #3.  len()求数据类型长度,获取字符串由多少个字符组成
    #对于中文字符串而言,在python3中中文直接对应汉字个数。
    #在python2.7中头部有utf8,一个汉字由三个字节组成,从而一个汉字算三个
    v = len[test]
    print(v)
    v1 = test.split('v')
    print(v1)                    #['tj','jlxm']
    #列表就是用中括号括起来,里面元素见用逗号分隔开,split得到的结果就是列表[11,2,2,58,'asjilnv']。用len求列表长度,就是求列表中逗号分隔出来了几个元素,不是列表具体元素长度相加
    
    #将原字符串一个个输出,用while实现
    test = "东南大学位于江苏省南京市"
    index = 0
    while index < len(test):
         v = test[index]
        print(v)
        index +=1
    print('========')
    
    #4. 用for语句实现,对应每个变量名item相当于index,每次循环自增一次,指向test中对应位置的字符
    #4. for语句中仍然支持break和continue
     for item in test: print(item)

    # 4. range()默认创建连续的整数。range(100)=range(0,100)
    # range(0,100,5)每五个创建一个,即第三个参数代表步长。通过设置步长从而创建不连续的整数
    # 在python2.7中会直接在内存中创建range指定个数的数字;
    # 但在python3当中range执行完不会立刻创建,只有开始调用for循环之后才会开始一个个按照循环次数需求创建
    test = range(100) #默认创建0-99
    for item in test: print(item)

    # 将文字对应的索引打印出来,而不是原字符串
    test = input(">>>")
    print(test) #qwe
    g = len(test)    #测长度3
    print(g)
    r = range(0,g) #(0,3)
    for item in r:
      print(item,test[item])
    0 q
    1 w
    2 e
    #将以上代码简化为:

      test = input(">>>")

      for item in range(0,len(test)):

      print(item,test[item]) 
     1 test = "alex"
     2 
     3 #首字母大写
     4 v = test.capitaliza()
     5 print(v)                      #结果Alex
     6 
     7 #将字符串中所有字符全部大写
     8 v7 = test.upper()
     9 print(v7)  
    10 
    11 #全体变小写
    12 v1 = test.casefold()    #更厉害,某些国家的也能变
    13 print(v1)
    14 v2 = test.lower()
    15 print(v2)
    16 
    17 #一共n=20个位置,将test字符串放中间
    18 test. center(20)    #空白处为空格填充
    19 test. center(20,"*")    #空白处为*填充
    20 test. center(20,"")    #空白处为"中"填充
    21 test. center(20,"9")    #空白处为9填充,但只能写一个字符。如99就不行
    22 
    23 #计算某字符/或者字符子序列在原字符串中出现的次数
    24 #count(self, sub, start=None, end=None)
    25 #将原字符串从0开始编号
    26 t = "alexalexrjs"
    27 v3 = t.count('e')   
    28 v4 = t.count('ex')    
    29 v5 = t.count('ex',5,6)    #从编号5位起,编号6位停止.计算ex出现次数
    30 print(v3)
    31 print(v4)
    32 print(v5)
    33 
    34 #查看字符串是不是以某字符/或字符子序列结尾ends,开头startswith
    35 #结果返回True/False
    36 #endswith(self, suffix, start=None, end=None)
    37 #startswith(self, suffix, start=None, end=None)
    38 v6 = test.endswith('e')
    39 print(v6)
    40 
    41 #在原字符串开始找相应字符子序列,找到后获取位置(从0开始编号)
    42 #若没找到,返回-1
    43 #find(self, sub, start=None, end=None)
    44 v8 = test.find('ex',5,7)
    45 print(v8)
    46 
    47 #格式化1:将字符串中的占位符替换为相应数值
    48 #format(*arg,**kwargs)
    49 t2 = 'i am {name}, age {a}'
    50 print(t2)                              #i am {name}, age {a}
    51 v9 = test.format(name='alex', a=19)        #'i am alex, age 19
    52 
    53 t3 = 'i am {0}, age {1}'               #从0编号依次开始替换占位符
    54 v10 = test.format('alex', 19)         #'i am alex, age 19
    55 
    56 #格式化2:传一个字典,格式上与format不一样了,但效果本质一样
    57 #format_map(self,mapping)
    58 v11 = test.format_map({"name":'alex', "a":19})
    59 #如果中括号内是name,就把alex替换
    60 
    61 #index找不到就直接报错。找到了就返回位置
    62 #find比index更好用,index语句可以忽略
    63 v12 = test.index('ex')
    64 print('v12')
    65 
    66 #isalnum(self)
    67 #检测字符串中只有数字、字母时为True,还有别的返回False
    68 t4 = "uasf890_+"
    69 v13 = t4.isalnum()
    70 print('v13')                                                      
    str函数列举
    #expandtabs()
    t1 = "12345678	9"
    v1 = t1.expandtabs(6)
    print(v,len(v))         
    #12345678    9  13 (其实78之后补4个空格,一起为6个位置)    
    #每六个一组,找里面有没有	,一旦出现	,则不看	之后的,把	和它之前的一组一起总占位6个。例如:若某一组为hsj	,则“hsj   ”	补三个空格,再从	之后重新开始新的组继续找。
    #用途:制成一个表格,从而按列对齐
    t2 = "username	email	password
    Josie	Josie@qq.com	124555
    Josie	Josie@qq.com	124555
    Josie	Josie@qq.com	124555
    Josie	Josie@qq.com	124555
    "      
    v2 = t2.expandtabs(20)
    #isalpha(self)只含字母、汉字
    #isalnum(self)只含数字
    #isdecimal()判定是否为数字(十进制小数),但这个用的多 
    #isdigit()判定是否为数字(还支持一些特殊形式的数字判别,如圈1)
    #isnumeric()判定是否为数字,支持中文‘二’
    #isidentifier()是否为标识符,只要满足由字母数字下划线组成就为True
    #islower(self)判断是不是全小写
    #lower()将字符串全部变成小写
    #isupper(self)判断是不是全大写
    #upper()将字符串全部变成大写
    #isprintable(self)在打印字符串的时候,是否存在不可显示的字符(如	,
    等)
    #isspace(self)判断是否全是空格
    #istitle(self)标题中每个单词首字母大写,title()可将字符串改成首字母全大写的形式,即变成标题
    
    #join()加字符串,在原来字符串中每个字符中加t对应字符串(t相当于分隔符)函数内部就是加循环
    test = "你是风儿我是沙"
    print(test)
    t = '   '
    v = t.join(test)
    print(v) 
    
    
    # ljust()与center(字符串放中间)对比,左边是原字符串,右边添加指定字符
    # rjust()右边是原字符串,左边添加指定字符
    # zfill()右边是原字符串,左边添加0
    test = "alex"
    v = test.1just(20,'*')
    print(v)
    v = t.join(test)
    print(v) 
    
    #lstrip()去掉左边空格,	 ,
    ,
    #rstrp()去掉右边空格,	 ,
    ,
    #strip()去掉左右空格,	 ,
    ,
    #在括号内可以自行添加别的想去除的字符串,找能匹配的最大子序列(正则匹配)
    test = "xalex"
    v = test.rstrip('9lexex')  #从右边开始
    print(v)
     1 #maketrans与translate一起用,maketrans先创建对应关系
     2 #translate进行对应关系的替换
     3 v1 = "jsdbvli;zxcjvo;jaeiouasu;igdvhb;9psdio"
     4 new_v1 = v1.maketrans("aeiou","12345")
     5 print(v1.translate(new_v1))  
    6

    7
    #partition()在test中找到括号内的字符(只算第一个)后,将原字符串以该字符分割成三份,从左边开始匹配。括号内只能传待匹配的字符参数。匹配分割后结果中仍有原字符,单独成一个字符串

    8
    #test.rpartition()从右边开始匹配
    9
    #test.split()只填字符默认把所有匹配的字符都划分开。若传匹配次数,则按匹配次数进行相应次数的分割。但原匹配字符(分隔符)会消失,即z不见了
    10 #test.rsplit()
    11 test = "dujhnvjzxnonlmzkd"
    12 v2 = test.partition('z')
    13 v3 = test.rpartition('z')
    14 v4 = test.split('z')
    15 v5 = test.rsplit('z')
    16 print(v2) #["dujhnvj","z","xnonlmzkd"]
    17 print(v3) #["dujhnvjzxnonlm","z","kd"]
    18 print(v4) #["dujhnvj","xnonlm","kd"]
    19 print(v5) #["dujhnvj","xnonlm","kd"]
    20 #用途:计算字符算数表达式:"1*2/3+5/7",通过partition分割提取到数字和运算表达式
    21
    22 #splitlines()只根据换行符 进行分割,根据True/False决定是否保留换行 若不写默认False,不保留换行符
    23 test = "dujh vjzx o lmzkd"
    24 v7 = test.splitlines() #['dujh','vjzx','o','lmzkd']
    25 v8 = test.splitlines(True) #['dujh ','vjzx ','o ','lmzkd']
    26 v2 = test.splitlines(False) #['dujh','vjzx','o','lmzkd']
    27
    28 #startwith()以某个字符开头
    29 #endswith()以某个字符结尾
    30 #swapcase()大小写转换
      1 class str(basestring):
      2     """
      3     str(object='') -> string
      4     
      5     Return a nice string representation of the object.
      6     If the argument is a string, the return value is the same object.
      7     """
      8     def capitalize(self):  
      9         """ 首字母变大写 """
     10         """
     11         S.capitalize() -> string
     12         
     13         Return a copy of the string S with only its first character
     14         capitalized.
     15         """
     16         return ""
     17 
     18     def center(self, width, fillchar=None):  
     19         """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
     20         """
     21         S.center(width[, fillchar]) -> string
     22         
     23         Return S centered in a string of length width. Padding is
     24         done using the specified fill character (default is a space)
     25         """
     26         return ""
     27 
     28     def count(self, sub, start=None, end=None):  
     29         """ 子序列个数 """
     30         """
     31         S.count(sub[, start[, end]]) -> int
     32         
     33         Return the number of non-overlapping occurrences of substring sub in
     34         string S[start:end].  Optional arguments start and end are interpreted
     35         as in slice notation.
     36         """
     37         return 0
     38 
     39     def decode(self, encoding=None, errors=None):  
     40         """ 解码 """
     41         """
     42         S.decode([encoding[,errors]]) -> object
     43         
     44         Decodes S using the codec registered for encoding. encoding defaults
     45         to the default encoding. errors may be given to set a different error
     46         handling scheme. Default is 'strict' meaning that encoding errors raise
     47         a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
     48         as well as any other name registered with codecs.register_error that is
     49         able to handle UnicodeDecodeErrors.
     50         """
     51         return object()
     52 
     53     def encode(self, encoding=None, errors=None):  
     54         """ 编码,针对unicode """
     55         """
     56         S.encode([encoding[,errors]]) -> object
     57         
     58         Encodes S using the codec registered for encoding. encoding defaults
     59         to the default encoding. errors may be given to set a different error
     60         handling scheme. Default is 'strict' meaning that encoding errors raise
     61         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
     62         'xmlcharrefreplace' as well as any other name registered with
     63         codecs.register_error that is able to handle UnicodeEncodeErrors.
     64         """
     65         return object()
     66 
     67     def endswith(self, suffix, start=None, end=None):  
     68         """ 是否以 xxx 结束 """
     69         """
     70         S.endswith(suffix[, start[, end]]) -> bool
     71         
     72         Return True if S ends with the specified suffix, False otherwise.
     73         With optional start, test S beginning at that position.
     74         With optional end, stop comparing S at that position.
     75         suffix can also be a tuple of strings to try.
     76         """
     77         return False
     78 
     79     def expandtabs(self, tabsize=None):  
     80         """ 将tab转换成空格,默认一个tab转换成8个空格 """
     81         """
     82         S.expandtabs([tabsize]) -> string
     83         
     84         Return a copy of S where all tab characters are expanded using spaces.
     85         If tabsize is not given, a tab size of 8 characters is assumed.
     86         """
     87         return ""
     88 
     89     def find(self, sub, start=None, end=None):  
     90         """ 寻找子序列位置,如果没找到,返回 -1 """
     91         """
     92         S.find(sub [,start [,end]]) -> int
     93         
     94         Return the lowest index in S where substring sub is found,
     95         such that sub is contained within S[start:end].  Optional
     96         arguments start and end are interpreted as in slice notation.
     97         
     98         Return -1 on failure.
     99         """
    100         return 0
    101 
    102     def format(*args, **kwargs): # known special case of str.format
    103         """ 字符串格式化,动态参数,将函数式编程时细说 """
    104         """
    105         S.format(*args, **kwargs) -> string
    106         
    107         Return a formatted version of S, using substitutions from args and kwargs.
    108         The substitutions are identified by braces ('{' and '}').
    109         """
    110         pass
    111 
    112     def index(self, sub, start=None, end=None):  
    113         """ 子序列位置,如果没找到,报错 """
    114         S.index(sub [,start [,end]]) -> int
    115         
    116         Like S.find() but raise ValueError when the substring is not found.
    117         """
    118         return 0
    119 
    120     def isalnum(self):  
    121         """ 是否是字母和数字 """
    122         """
    123         S.isalnum() -> bool
    124         
    125         Return True if all characters in S are alphanumeric
    126         and there is at least one character in S, False otherwise.
    127         """
    128         return False
    129 
    130     def isalpha(self):  
    131         """ 是否是字母 """
    132         """
    133         S.isalpha() -> bool
    134         
    135         Return True if all characters in S are alphabetic
    136         and there is at least one character in S, False otherwise.
    137         """
    138         return False
    139 
    140     def isdigit(self):  
    141         """ 是否是数字 """
    142         """
    143         S.isdigit() -> bool
    144         
    145         Return True if all characters in S are digits
    146         and there is at least one character in S, False otherwise.
    147         """
    148         return False
    149 
    150     def islower(self):  
    151         """ 是否小写 """
    152         """
    153         S.islower() -> bool
    154         
    155         Return True if all cased characters in S are lowercase and there is
    156         at least one cased character in S, False otherwise.
    157         """
    158         return False
    159 
    160     def isspace(self):  
    161         """
    162         S.isspace() -> bool
    163         
    164         Return True if all characters in S are whitespace
    165         and there is at least one character in S, False otherwise.
    166         """
    167         return False
    168 
    169     def istitle(self):  
    170         """
    171         S.istitle() -> bool
    172         
    173         Return True if S is a titlecased string and there is at least one
    174         character in S, i.e. uppercase characters may only follow uncased
    175         characters and lowercase characters only cased ones. Return False
    176         otherwise.
    177         """
    178         return False
    179 
    180     def isupper(self):  
    181         """
    182         S.isupper() -> bool
    183         
    184         Return True if all cased characters in S are uppercase and there is
    185         at least one cased character in S, False otherwise.
    186         """
    187         return False
    188 
    189     def join(self, iterable):  
    190         """ 连接 """
    191         """
    192         S.join(iterable) -> string
    193         
    194         Return a string which is the concatenation of the strings in the
    195         iterable.  The separator between elements is S.
    196         """
    197         return ""
    198 
    199     def ljust(self, width, fillchar=None):  
    200         """ 内容左对齐,右侧填充 """
    201         """
    202         S.ljust(width[, fillchar]) -> string
    203         
    204         Return S left-justified in a string of length width. Padding is
    205         done using the specified fill character (default is a space).
    206         """
    207         return ""
    208 
    209     def lower(self):  
    210         """ 变小写 """
    211         """
    212         S.lower() -> string
    213         
    214         Return a copy of the string S converted to lowercase.
    215         """
    216         return ""
    217 
    218     def lstrip(self, chars=None):  
    219         """ 移除左侧空白 """
    220         """
    221         S.lstrip([chars]) -> string or unicode
    222         
    223         Return a copy of the string S with leading whitespace removed.
    224         If chars is given and not None, remove characters in chars instead.
    225         If chars is unicode, S will be converted to unicode before stripping
    226         """
    227         return ""
    228 
    229     def partition(self, sep):  
    230         """ 分割,前,中,后三部分 """
    231         """
    232         S.partition(sep) -> (head, sep, tail)
    233         
    234         Search for the separator sep in S, and return the part before it,
    235         the separator itself, and the part after it.  If the separator is not
    236         found, return S and two empty strings.
    237         """
    238         pass
    239 
    240     def replace(self, old, new, count=None):  
    241         """ 替换 """
    242         """
    243         S.replace(old, new[, count]) -> string
    244         
    245         Return a copy of string S with all occurrences of substring
    246         old replaced by new.  If the optional argument count is
    247         given, only the first count occurrences are replaced.
    248         """
    249         return ""
    250 
    251     def rfind(self, sub, start=None, end=None):  
    252         """
    253         S.rfind(sub [,start [,end]]) -> int
    254         
    255         Return the highest index in S where substring sub is found,
    256         such that sub is contained within S[start:end].  Optional
    257         arguments start and end are interpreted as in slice notation.
    258         
    259         Return -1 on failure.
    260         """
    261         return 0
    262 
    263     def rindex(self, sub, start=None, end=None):  
    264         """
    265         S.rindex(sub [,start [,end]]) -> int
    266         
    267         Like S.rfind() but raise ValueError when the substring is not found.
    268         """
    269         return 0
    270 
    271     def rjust(self, width, fillchar=None):  
    272         """
    273         S.rjust(width[, fillchar]) -> string
    274         
    275         Return S right-justified in a string of length width. Padding is
    276         done using the specified fill character (default is a space)
    277         """
    278         return ""
    279 
    280     def rpartition(self, sep):  
    281         """
    282         S.rpartition(sep) -> (head, sep, tail)
    283         
    284         Search for the separator sep in S, starting at the end of S, and return
    285         the part before it, the separator itself, and the part after it.  If the
    286         separator is not found, return two empty strings and S.
    287         """
    288         pass
    289 
    290     def rsplit(self, sep=None, maxsplit=None):  
    291         """
    292         S.rsplit([sep [,maxsplit]]) -> list of strings
    293         
    294         Return a list of the words in the string S, using sep as the
    295         delimiter string, starting at the end of the string and working
    296         to the front.  If maxsplit is given, at most maxsplit splits are
    297         done. If sep is not specified or is None, any whitespace string
    298         is a separator.
    299         """
    300         return []
    301 
    302     def rstrip(self, chars=None):  
    303         """
    304         S.rstrip([chars]) -> string or unicode
    305         
    306         Return a copy of the string S with trailing whitespace removed.
    307         If chars is given and not None, remove characters in chars instead.
    308         If chars is unicode, S will be converted to unicode before stripping
    309         """
    310         return ""
    311 
    312     def split(self, sep=None, maxsplit=None):  
    313         """ 分割, maxsplit最多分割几次 """
    314         """
    315         S.split([sep [,maxsplit]]) -> list of strings
    316         
    317         Return a list of the words in the string S, using sep as the
    318         delimiter string.  If maxsplit is given, at most maxsplit
    319         splits are done. If sep is not specified or is None, any
    320         whitespace string is a separator and empty strings are removed
    321         from the result.
    322         """
    323         return []
    324 
    325     def splitlines(self, keepends=False):  
    326         """ 根据换行分割 """
    327         """
    328         S.splitlines(keepends=False) -> list of strings
    329         
    330         Return a list of the lines in S, breaking at line boundaries.
    331         Line breaks are not included in the resulting list unless keepends
    332         is given and true.
    333         """
    334         return []
    335 
    336     def startswith(self, prefix, start=None, end=None):  
    337         """ 是否起始 """
    338         """
    339         S.startswith(prefix[, start[, end]]) -> bool
    340         
    341         Return True if S starts with the specified prefix, False otherwise.
    342         With optional start, test S beginning at that position.
    343         With optional end, stop comparing S at that position.
    344         prefix can also be a tuple of strings to try.
    345         """
    346         return False
    347 
    348     def strip(self, chars=None):  
    349         """ 移除两段空白 """
    350         """
    351         S.strip([chars]) -> string or unicode
    352         
    353         Return a copy of the string S with leading and trailing
    354         whitespace removed.
    355         If chars is given and not None, remove characters in chars instead.
    356         If chars is unicode, S will be converted to unicode before stripping
    357         """
    358         return ""
    359 
    360     def swapcase(self):  
    361         """ 大写变小写,小写变大写 """
    362         """
    363         S.swapcase() -> string
    364         
    365         Return a copy of the string S with uppercase characters
    366         converted to lowercase and vice versa.
    367         """
    368         return ""
    369 
    370     def title(self):  
    371         """
    372         S.title() -> string
    373         
    374         Return a titlecased version of S, i.e. words start with uppercase
    375         characters, all remaining cased characters have lowercase.
    376         """
    377         return ""
    378 
    379     def translate(self, table, deletechars=None):  
    380         """
    381         转换,需要先做一个对应表,最后一个表示删除字符集合
    382         intab = "aeiou"
    383         outtab = "12345"
    384         trantab = maketrans(intab, outtab)
    385         str = "this is string example....wow!!!"
    386         print str.translate(trantab, 'xm')
    387         """
    388 
    389         """
    390         S.translate(table [,deletechars]) -> string
    391         
    392         Return a copy of the string S, where all characters occurring
    393         in the optional argument deletechars are removed, and the
    394         remaining characters have been mapped through the given
    395         translation table, which must be a string of length 256 or None.
    396         If the table argument is None, no translation is applied and
    397         the operation simply removes the characters in deletechars.
    398         """
    399         return ""
    400 
    401     def upper(self):  
    402         """
    403         S.upper() -> string
    404         
    405         Return a copy of the string S converted to uppercase.
    406         """
    407         return ""
    408 
    409     def zfill(self, width):  
    410         """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
    411         """
    412         S.zfill(width) -> string
    413         
    414         Pad a numeric string S with zeros on the left, to fill a field
    415         of the specified width.  The string S is never truncated.
    416         """
    417         return ""
    418 
    419     def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
    420         pass
    421 
    422     def _formatter_parser(self, *args, **kwargs): # real signature unknown
    423         pass
    424 
    425     def __add__(self, y):  
    426         """ x.__add__(y) <==> x+y """
    427         pass
    428 
    429     def __contains__(self, y):  
    430         """ x.__contains__(y) <==> y in x """
    431         pass
    432 
    433     def __eq__(self, y):  
    434         """ x.__eq__(y) <==> x==y """
    435         pass
    436 
    437     def __format__(self, format_spec):  
    438         """
    439         S.__format__(format_spec) -> string
    440         
    441         Return a formatted version of S as described by format_spec.
    442         """
    443         return ""
    444 
    445     def __getattribute__(self, name):  
    446         """ x.__getattribute__('name') <==> x.name """
    447         pass
    448 
    449     def __getitem__(self, y):  
    450         """ x.__getitem__(y) <==> x[y] """
    451         pass
    452 
    453     def __getnewargs__(self, *args, **kwargs): # real signature unknown
    454         pass
    455 
    456     def __getslice__(self, i, j):  
    457         """
    458         x.__getslice__(i, j) <==> x[i:j]
    459                    
    460                    Use of negative indices is not supported.
    461         """
    462         pass
    463 
    464     def __ge__(self, y):  
    465         """ x.__ge__(y) <==> x>=y """
    466         pass
    467 
    468     def __gt__(self, y):  
    469         """ x.__gt__(y) <==> x>y """
    470         pass
    471 
    472     def __hash__(self):  
    473         """ x.__hash__() <==> hash(x) """
    474         pass
    475 
    476     def __init__(self, string=''): # known special case of str.__init__
    477         """
    478         str(object='') -> string
    479         
    480         Return a nice string representation of the object.
    481         If the argument is a string, the return value is the same object.
    482         # (copied from class doc)
    483         """
    484         pass
    485 
    486     def __len__(self):  
    487         """ x.__len__() <==> len(x) """
    488         pass
    489 
    490     def __le__(self, y):  
    491         """ x.__le__(y) <==> x<=y """
    492         pass
    493 
    494     def __lt__(self, y):  
    495         """ x.__lt__(y) <==> x<y """
    496         pass
    497 
    498     def __mod__(self, y):  
    499         """ x.__mod__(y) <==> x%y """
    500         pass
    501 
    502     def __mul__(self, n):  
    503         """ x.__mul__(n) <==> x*n """
    504         pass
    505 
    506     @staticmethod # known case of __new__
    507     def __new__(S, *more):  
    508         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
    509         pass
    510 
    511     def __ne__(self, y):  
    512         """ x.__ne__(y) <==> x!=y """
    513         pass
    514 
    515     def __repr__(self):  
    516         """ x.__repr__() <==> repr(x) """
    517         pass
    518 
    519     def __rmod__(self, y):  
    520         """ x.__rmod__(y) <==> y%x """
    521         pass
    522 
    523     def __rmul__(self, n):  
    524         """ x.__rmul__(n) <==> n*x """
    525         pass
    526 
    527     def __sizeof__(self):  
    528         """ S.__sizeof__() -> size of S in memory, in bytes """
    529         pass
    530 
    531     def __str__(self):  
    532         """ x.__str__() <==> str(x) """
    533         pass
    534 
    535 str
    Str函数定义

    字符串常用功能:

    • 移除空白
    • 分割
    • 长度
    • 索引
    • 切片
    注意:字符串一旦创建就不可修改,如果修改将会创建一个新的字符串。例如字符串做加法时,将新开辟一个内存来存放新的和字符串。
    内存中空间是连续的。
    #replace()替换指定字符串,并可以加上替换次数
    test =  "aljjalbdalhalikal"
    v = test.replace("al",'ixjhznasj')
    v = test.replace("al",'ixjhznasj',2)
    print(v)
    print(v1)
    # formate
    template = "i am {name}, age : {age}"
    v = template.formate(name = ‘alex’, 'age' = 19)  #正确传值法
    print(v)
    
    #v = template.formate({'name' : ‘alex’, 'age' : 19)   #formate中参数传字典,不能直接这么写会报错,加两个**在字典前面
    
    v = template.formate(**{'name' : ‘alex’, 'age' : 19)
    print(v)
    
    #补充:在查阅这些函数的def时,如果看到参数列表中**kwargs,表示可以通过在字典前加两个**的方式传入字典作为参数
    4、列表list
    创建列表对象name_list:
    name_list = ['alex', 'seven', 'eric']
    
    name_list = list(['alex', 'seven', 'eric'])

    1). 列表里还能嵌套列表,可以无限嵌套。列表相当于集合,其中元素可以是任意数据类型

    2). 逗号分割,[  ]括起来

    3). 可以通过切片取值list[3:5]结果为列表、索引取值 li[3]

         寻找嵌套内列表的值   li[4][1][0]会得到19;如果再加一个[1],将得到9 。即 li[4][1][0][1] = 9

    4). 支持for   while循环  break continue   

    5). 列表可以被删除(可以通过索引、切片删 del li[1]   del li[1:6])、修改:可以通过索引修改,也可以通过切片修改:li[1:3] = [120,190])

    列表内并非连续存,以 链表形式存:存本元素及下一元素的地址,不用重新开辟内存。从而可以修改他的数值,同时修改它其中的元素地址值就可以了。

    li[1] = 120
    print(li)
    li[1] = [11,22,33,44]
    print(li)
    
    li[1:3] = [120,90]
    print(li)
    #对比字符串:
        s = ’alex‘     
        s[0] = 'e'    #直接报错
    # 字符串修改:
        s = ’alex‘
        s = s.replace('l','el')     #此时变量名s就是一个指向    
    ### 补充:字符串创建后,不可修改。指的是不可用索引方式修改
    # replace方法看似是修改了,实质:在创建了一个内存,让v重新指向新的字符串

    6). 用in判断在不在字符串中,看list中整体在不在,如下例子中‘abc’就不能算是一个列表元素,逗号分隔开的才是一个整体元素

    ["abc", [19,28], 89, "hhjjkk"]这个整体才算是一个元素
    li = [1,12,13,"age",["abc", [19,28], 89, "hhjjkk"], "alex", True]
    v = “age” in li

    7). 字符串转列表:直接默认一个个字符输出来。实质就是进行多次循环

    name = "alexfdvsdgsrgrsfg"
    l = list(name)
    print(l)

    # 输出结果:['a', 'l', 'e', 'x', 'f', 'd', 'v', 's', 'd', 'g', 's', 'r', 'g', 'r', 's', 'f', 'g']

    8). 当l 为一个数字的时候不能循环:   因此数字也不能转换为列表。

      可以推测出,在转化为列表时,实质进行的是for循环,每次把待转换数据的一个元素作为列表的一个元素,而数字不能进行for循环,自然也不能转化为列表了

    s = 123
    for i in s:
        print(i)    #会报错

     9). 将列表转化为字符串

    li = ["abc", [19,28], 89, "hhjjkk"]
    #思路1: l
    = str(li) print(l) #结果["abc", [19,28], 89, "hhjjkk"],无论给str一个什么样的数值,Str都直接把此变量加上引号变字符串了,不能达到我们想要的效果
    #思路2:
    (列表中既有数字又有字符串)利用for循环一个个处理,且只能解锁一次。即里面如果还有列表则还需进一步处理
    for i in li:
      s = s + str(i)
    print(s)
    #思路3:(列表中只有字符串)直接使用字符串独有的join, join()内部实质也是在做for循环,帮你把他们拼接起来
    li = ["123","456"]
    v = "".join(li)
    print(v)

    基本操作:

    • 索引
    • 切片
    • 追加
    • 删除
    • 长度
    • 切片
    • 循环
    • 包含 
    list的魔法
    #######################################灰魔法: list类中提供的方法 #######################################
    li = [11, 22, 33, 22, 44]
    1. append()原来值最后追加
    # 对象.方法(..)    li对象调用append方法,括号内可以传参数
    li.append(5)     #直接在原值后面追加,无需找一个变量来接收它,即   li = [11, 22, 33, 22, 44, 5]
    v = li.append(5) #打印v的值为None。与字符串中方法做区别。根本原因:list能修改,而字符串不能修改
    li.append("alex")        #python中None表示空值,什么都不是
    li.append([1234,2323])
    print(li)
    
    2 清空列表
    li.clear()
    print(li)
    
    3 拷贝,浅拷贝
    v = li.copy()
    print(v)
    
    4. 计算元素出现的次数count(self,value)
    v = li.count(22)
    print(v)
    
    5. extend()扩展原列表,参数:可迭代对象
    li = [11, 22, 33, 22, 44]
    li.append([9898,"不得了"])        #[11, 22, 33, 22, 44, [9898, '不得了']]
    
    li.extend([9898,"不得了"])      #[11, 22, 33, 22, 44,9898,'不得了']
    #extend中相当于执行了以下循环
    for i in [9898,"不得了"]:
        li.append(i)
    #[11, 22, 33, 22, 44, 9898, '不得了']
    #append()直接把字符串当成一个列表元素附在原列表的最后
    
    li.extend("不得了")            
    print(li)
    #[11, 22, 33, 22, 44, 9898, '不','得','了']
    #extend()会将传入的字符串也进行for循环拆成三个字符分别作为列表的一个元素
    
    6. index根据值获取当前值索引位置(左边优先)
    li = [11, 22, 33, 22, 44]
    v= li.index(22)             #1
    print(v)
    
    7. insert在指定索引位置插入元素
    li = [11, 22, 33, 22, 44]
    li.insert(0,99)                #在第0个位置插入99
    print(li)
    #[99, 11, 22, 33, 22, 44]
    
    8. pop()删除某个值(1.指定索引;2. 默认最后一个),并获取删除的值
    li = [11, 22, 33, 22, 44]
    v = li.pop()    #pop删除li中的数值,并获取到被删除的的只
    print(li)
    print(v)
    #[11, 22, 33, 22]          44
    
    li = [11, 22, 33, 22, 44]
    v = li.pop(1)
    print(li)
    print(v)
    #[11, 33, 22, 44]        22
    
    9. remove()删除列表中的指定值,左边优先
    li = [11, 22, 33, 22, 44]
    li.remove(22)
    print(li)
    # [11, 33, 22, 44]
    
    PS:有关删除的指令 pop remove    del li[0]    del li[7:9]   clear
    
    10. reverse()将当前列表进行翻转
    li = [11, 22, 33, 22, 44]
    li.reverse()
    print(li)
    #[44, 22, 33, 22, 11]
    
    11 sort()列表的排序
    li = [11,44, 22, 33, 22]
    li.sort()                 #[11, 22, 22, 33, 44]  不写参数,默认从小到大排序
    li.sort(reverse=True)   #[44, 33, 22, 22,11]   从大到小排
    print(li)
    
    # 函数的排序方法
    cmp
    key
    sorted
    ####################dict功能方法###########################################################################
    
    clear(), copy(), keys, 
    dic = {
        "k1": 'v1',            #键值对
        "k2": 'v2'
    }
    # 1 fromkeys()根据序列,创建字典,并指定统一的值
    v = dict.fromkeys(["k1",123,"999"])         #生成字典序列,key分别为"k1",123,"999",不指定默认为None
    print(v)                                    #{"k1": None,123: None,"999": None}
    v = dict.fromkeys(["k1",123,"999"],456)     #{"k1": 456,123: 456,"999": 456}
    
    # 2 get()根据Key获取值,key不存在时,可以指定默认值(None)
    v = dic['k1']
    print(v)                    #v1
    v = dic['k11111']
    print(v)                    #直接报错,没有这个key
    v = dic.get('k1')    
    print(v)                    #v1
    v = dic.get('k11111')
    print(v)                    #None   不会尴尬地报错
    v = dic.get('k11111',meiyou)
    print(v)                    #如果key不存在,则直接返回你指定的参数meiyou
    
    # 3 pop()删除并获取值
    dic = {
        "k1": 'v1',
        "k2": 'v2'
    }
    v = dic.pop('k1')       #直接删对应键值对,并利用v得到移除的数值
    v = dic.pop('k1',90)    #如果key不存在,则直接返回你指定的参数值90
    print(dic,v)
    k,v = dic.popitem()        #随机删键值对
    print(dic,k,v)            
    
    # 4 setdefault()设置值,
    dic = {
        "k1": 'v1',
        "k2": 'v2'
    }
    v = dic.setdefault('k1','123')        #已存在,不设置,获取当前key对应的值
    print(dic,v)                        #{"k1": 'v1',"k2": 'v2'}   v1
    v = dic.setdefault('k1111','123')    #不存在,设置,获取当前key对应的新值
    print(dic,v)                        #{"k1": 'v1',"k2": 'v2','k1111','123'}   123
    
    # 5 update()更新
    dic = {
        "k1": 'v1',
        "k2": 'v2'
    }
    dic.update({'k1': '111111','k3': 123})        #k1本来有,将原来的k1对应的值更新;k3本来没有,将k3键值对添加进来
    print(dic)                                    #{"k2": 'v2','k1': '111111','k3': 123}
    dic.update(k1=123,k3=345,k5="asdf")            #参数写成这种形式,python默认将其转化为一个字典,自行更新。
    print(dic)                                    ##{"k2": 'v2','k1': 123,'k3': 345, 'k5': 'asdf'}
    
    # 最常用的:6 keys()  7 values()   8 items()   get   update
    ##########

    5、元祖tuple

    创建元祖:
    ages = (11, 22, 33, 44, 55)
    或
    ages = tuple((11, 22, 33, 44, 55))
    基本操作:
    • 索引
    • 切片
    • 循环
    • 长度
    • 包含
    ####################################### 深灰魔法 #######################################
    # 1. 书写格式
    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    # 一般写元组的时候,推荐在最后加入一个逗号,为了与方法函数相区别。加在元祖中不报错也不影响元祖参数个数,函数中会报错。
    # 元素不可被(索引)修改,不能被增加或者删除 
      tu[0] = 123   #直接报错
    
    # 2. 可以索引取值
        v = tu[0]
        print(v)
    
    # 3. 可以切片取值
        v = tu[0:2]
        print(v)
    
    # 4. 可以被for循环,可迭代对象(列表、元祖、字符串)
        for item in tu:
            print(item)
    
    # 5. 转换
        s = "asdfasdf0"
        li = ["asdf","asdfasdf"]
        tu = ("asdf","asdf")
    #字符串可转元祖,列表可以和元祖相互转化
        v = tuple(s)
        print(v)
        v = tuple(li)
        print(v)
        v = list(tu)
        print(v)
    # 将元祖转化为字符串,当元祖里只有字符串的时候才可以利用join,否则得自己写for循环并在每个元祖元素之间用下划线分割
        v = "_".join(tu)
        print(v)                #asdf_asdf
    # extend()对列表/元祖进行拓展
        li = ["asdf","asdfasdf"]
        li.extend((11,22,33,))
        print(li)                            
    #["asdf","asdfasdf",11,22,33,]    直接将元祖中的元素加入到列表当中
    
    # 6.元组的一级元素不可修改/删除/增加,下一级看下一级是什么数据类型
    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    # 元组,有序。
        v = tu[3][0][0]    
        print(v)            #得到33
        v=tu[3]                
        print(v)            #得到[(33,44)]为一个列表,而列表可以被修改
    tu[3][0] = 567            #tu[3][0]为列表可以改
    print(tu)                #直接写tu就能输出上行的指定值
    tu[3][0][0] = (55,466)            #报错,tu[3][0][0]=(33,44)为元祖不可以改
    #元祖中提供的只有两种方法
    #    count(self,value)获取指定元素在元组中出现的次数
       tu.count(22)
    # index(self,value)获取指定元素在元组中的索引值,左边优先
       tu.index(22)

    三种数据类型之间对比:
    字符串:只能保存一个整体,难以分类。除非在存的时候可以用分隔符先分隔好,然后用split来划分开。修改时还需要把特定的改了之后存到一个新的里面。
    列表:便于修改,改动某一元素之后,其他元素依旧不会受到影响
    元祖:如果创建的元素不允许修改,归到一类中。内部不能直接操作,如果想改转换为列表

     6、字典(无序)dict

    创建字典:键值对
    person = {"name": "mr.wu", 'age': 18}
    或
    person = dict({"name": "mr.wu", 'age': 18})

    常用操作:

    • 索引
    • 新增
    • 删除
    • 键、值、键值对
    • 循环
    • 长度
    # 1、基本结构
    info = {
        "k1": "v1", # 键值对   "key": "value"
        "k2": "v2"
    }
    #### 2 字典的value可以是任何值,且可以嵌套
    info = {
        "k1": 18,
        "k2": True,
        "k3": [
            11,
            [],
            (),
            22,
            33,
            {
                'kk1': 'vv1',
                'kk2': 'vv2',
                'kk3': (11,22),
            }
        ],
        "k4": (11,22,33,44)
    }
    print(info)                 #可以成功打印
    
    ####  3 列表、字典不能作为字典的key,即冒号前面的
    info ={
        1: 'asdf',                #数字可以
        "k1": 'asdf',            #字符串可以(字符串不可被修改)
        True: "123",            #bool可以,但是由于True为1与第一个key重复了,这样会随机出现字典中对应。
        # [11,22]: 123            #报错,列表不可以(列表可以被修改)
        (11,22): 123,            #元祖可以(元祖不可被修改)
        # {'k1':'v1'}: 123
    }
    print(info)
    # 本质原因:字典在保存的时候是按照hash表去保存的。内存中生成的全变为hash数值。而列表不支持直接转化为hash值
    
    True 1  False 0
    info ={
        "k1": 'asdf',
        True: "123",     #这样就不会有1的key,没有任何问题
        # [11,22]: 123
        (11,22): 123,
        # {'k1':' v1'}: 123
    
    }
    print(info)
    
    # 4 字典无序
    
    info = {
        "k1": 18,
        "k2": True,
        "k3": [
            11,
            [],
            (),
            22,
            33,
            {
                'kk1': 'vv1',
                'kk2': 'vv2',
                'kk3': (11,22),
            }
        ],
        "k4": (11,22,33,44)
    }
    print(info)                    # 每次打印出来的顺序都随机,说明无序
    
    # 5、索引(自己定义的key来找)方式找到指定元素; 但是不能通过切片的方式来寻找,因为无顺序
    info = {
        "k1": 18,
        2: True,
        "k3": [
            11,
            [],
            (),
            22,
            33,
            {
                'kk1': 'vv1',
                'kk2': 'vv2',
                'kk3': (55,66),
            }
        ],
        "k4": (77,88,99,00)
    }
    v = info['k1']
    print(v)        #18
    v = info[2]
    print(v)        #True
    v = info['k3'][5]['kk3'][0]
    print(v)        #55
    
    # 6 字典支持 del 删除,删键值对(与key和索引结合)
    info = {
        "k1": 18,
        2: True,
        "k3": [
            11,
            [],
            (),
            22,
            33,
            {
                'kk1': 'vv1',
                'kk2': 'vv2',
                'kk3': (11,22),
            }
        ],
        "k4": (11,22,33,44)
    }
    del info['k1']
    
    del info['k3'][5]['kk1']
    print(info)
    
    # 7 for循环可以,while是一个个递增递减,但字典不是有序地
    info = {
        "k1": 18,
        2: True,
        "k3": [
            11,
            [],
            (),
            22,
            33,
            {
                'kk1': 'vv1',
                'kk2': 'vv2',
                'kk3': (11,22),
            }
        ],
        "k4": (11,22,33,44)
    }
    for item in info:
        print(item)                        #k3 k4 k1 2    #默认for循环输出只有key且依旧乱序
    
    for item in info.keys():            #k1 k4 k3 2    #默认for循环输出只有key且依旧乱序,与默认的一样
        print(item)
    
    for item in info.values():            #只输出values,而且每行输出一字典元素的value
        print(item)
    
    for item in info.keys():            #item 为每次得到的key,则info[item]对应此key的value值
        print(item,info[item])            #输出完整键值对
    
    for k,v in info.items():            #输出键值对,k对应key,v对应value
        print(k,v)

     7.集合

    定义:由不同元素组成的,集合中是一组无序排列的可hash值 (不可变类型),可以作为字典的key
    特性:目的是为了将不同值存放到一起,不同集合间用
     
    #集合的定义[1,2,3,4]或者用set 
    s=set('hello')        #set中写可迭代类型
    print(s)              #{'o','h','l','e'}    set将自动删去重复字符生成集合
    
    s=set(['alex','alex','sb'])    
    print(s)                        #{'alex','sb'}
    
    # s={1,2,3,4,5,6}
    
    ######集合内置方法
    #add()添加
    s.add('s')    #{1,2,3,'s',4,5,6}
    s.add('3')    #字符串类型的'3'可以加进来{1,2,3,'3',4,5,'s',6}
    s.add(3)        #重复的数字3,可以运行,但集合中只有一个元素
    print(s)
    
    # 清空clear()
    s.clear()
    print(s)    #set()      #表示s被清空了
    
    # 拷贝copy()
    s1=s.copy()               #s1和s一模一样
    
    #随机删pop()
    s={'sb',1,2,3,4,5,6}
    s.pop()                    #随机出现删除一个元素
    
    #指定删除remove()   discard()
    s.remove('sb')
    s.remove('hellol')    #删除元素不存在会报错
    s.discard('sbbbb')    #删除元素不存在不会报错
    print(s)
    
    # 利用集合完成关系测试
    #Q :统计出既在python_l,又在linux_l中的元素
    python_l=['lcg','szw','zjw','lcg']
    linux_l=['lcg','szw','sb']
    p_s=set(python_l)
    l_s=set(linux_l)
    
    #如果不用集合,用循环语句输出交集部分
    python_linux = []
    for p_name in python_l:
        if p_name in linux_l:
            python_linux.append(p_name)
    print(python_linux)
    
    #求交集  intersection()
    print(p_s,l_s)      #分别打印两个集合{'lcg','szw','zjw'} {'lcg','szw','sb'}
    print(p_s.intersection(l_s))    #{'lcg','szw'}
    print(p_s&l_s)                    #{'lcg','szw'}
    #求并集   union()
    print(p_s.union(l_s))            #{'lcg','szw','zjw','sb'}
    print(p_s|l_s)                    #{'lcg','szw','zjw','sb'}
    #差集    difference()  被
    print('差集',p_s-l_s)
    print(p_s.difference(l_s))      #{'zjw','lcg'}
    print('差集',l_s-p_s)
    print(l_s.difference(p_s))        #{'sb'}
    #交叉补集:先把两个集合放在一起然后去掉相同部分,两集合的剩下部分
    print('交叉补集',p_s.symmetric_difference(l_s))        #{'sb','zjw'}
    print('交叉补集',p_s^l_s)
    
    
    python_l=['lcg','szw','zjw','lcg']
    linux_l=['lcg','szw','sb']
    p_s=set(python_l)
    l_s=set(linux_l)
    print(p_s,l_s)                #{'lcg','szw','zjw'} {'lcg','szw','sb'}
    print('差集',p_s-l_s)        #{'zjw','lcg'}
    
    #difference_update()求差集并更新
    p_s=p_s-l_s                    #如果不重新赋值回p_s,p_s和l_s的数值不会变化
    p_s.difference_update(l_s) #等价于p_s=p_s-l_s    
    print(p_s)
    
    #isdisjoint()如果s1和s2没有交集
    s1={1,2}
    s2={2,3,5}
    print(s1.isdisjoint(s2))   #如果s1和s2没有交集,则返回True
    
    #issubset()子sub集    issuperset()父super集
    s1={1,2}
    s2={1,2,3}
    print(s1.issubset(s2)) #True    s1 是s2 的子集
    print(s2.issubset(s1)) #False
    
    print(s2.issuperset(s1))#s1 是s2 的父集
    
    #update()可迭代的数据类型都可以更新
    s1={1,2}
    s2={1,2,3}
    s1.update(s2)       #更新多个值s1={1,2,3}
    
    #add()附加
    s1.add(1,2,3,4)     #更新一个值
    s1.union(s2)         #不更新s1,整个表达式产生了一个数据结果,需要一个新变量去接收它
    print(s1)
    
    #print()
    s=frozenset('hello')
    print(s)
    names=['alex','alex','wupeiqi']
    
    names=list(set(names))
    print(names)
     
    PS:循环,range,continue 和 break
    ####################### 整理 #################
    
    一、数字      int(..)
    
    二、字符串
    最常用的:replace/find/join/strip去空白/startswith/endswith/split/upper/lower/format模板占位符
    
    tempalte = "i am {name}, age : {age}"
    v = tempalte.format(name='alex',age=19) 通常是这样传两个赋值表达式
    v = tempalte.format(**{"name": 'alex','age': 19})  但如果想要传字典,应该在字典前面加入两个*
    print(v)
    
    三、列表
    最常用的append、extend、insert
    索引、切片、循环、in
    
    四、元组
    忽略
    索引、切片、循环,in         以及元素不能被修改
    
    五、字典
    get/update/keys/values/items
    for,索引
    
    dic = {"k1": 'v1}
    v = "k1" in dic            #默认循环key,如果写v1会报错,需要用值判断时,用下面的dic.values()
    print(v)
    
    v = "v1" in dic.values()
    print(v)
    
    六、布尔值
    True 1  False 0
    bool(...)
    None ""  () []  {} 0 ==> False    其他全是真
     1 ###类型可变(id不变):列表、字典
     2 ###不可变(id变了):数字、字符串、元祖
     3 
     4 #对于字符串
     5 name = 'alex'                   #开辟内存空间来存放变量值‘alex’,变量名name用来取变量的值
     6 id(name)          #18107672
     7 name = 'sb'                          #开辟新的内存空间来存放变量值‘sb’,
     8 id(name)      #18107784     id号不同表示name指向了不同的内存   
     9 
    10 #对于列表
    11 hobby = ['coding', ' play']
    12 id(hobby)                         #18113928
    13 hobby{0} = 'sb'              #修改列表的第一个值
    14 id(hobby)                        #18113928    id值不变,说明原来内存位置的数值已经更改了
    15 
    16 #对于字典
    17 dic = ['name' : 'alex']
    18 id(dic)                         #4568008
    19 dic['name'] = 'sb'
    20 id(dic)                         #4568008
    ###访问数据
    1.顺序访问:字符串、列表、元祖
    2.映射:字典
    3. 直接访问:数字(变量名直接全体一次性访问)
    字典查询速度比列表快,但字典占的内存比列表大
    
    ####存放元素个数:
    1.容器类型:列表、元祖、字典
    2.原子类型:数字、字符串

    其他

    1、for循环
    用户按照顺序循环可迭代对象中的内容,
    PS:break、continue
    1
    2
    3
    li = [11,22,33,44]
    for item in li:
        print item
    2、enumrate
    为可迭代的对象添加序号
    1
    2
    3
    li = [11,22,33]
    for k,v in enumerate(li, 1):
        print(k,v)
    3、range和xrange
    指定范围,生成指定的数字
    1
    2
    3
    4
    5
    6
    7
    8
    print range(110)
    # 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
     
    print range(1102)
    # 结果:[1, 3, 5, 7, 9]
     
    print range(300-2)
    # 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]  

    练习题

    一、元素分类

    有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
    即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

    二、查找
    查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
        li = ["alec", " aric", "Alex", "Tony", "rain"]
        tu = ("alec", " aric", "Alex", "Tony", "rain") 
        dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
     
    三、输出商品列表,用户输入序号,显示用户选中的商品
        商品 li = ["手机", "电脑", '鼠标垫', '游艇']
     
    四、购物车

    功能要求:

    • 要求用户输入总资产,例如:2000
    • 显示商品列表,让用户根据序号选择商品,加入购物车
    • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
    • 附加:可充值、某商品移除购物车
    1
    2
    3
    4
    5
    6
    goods = [
        {"name""电脑""price"1999},
        {"name""鼠标""price"10},
        {"name""游艇""price"20},
        {"name""美女""price"998},
    ]

     五、用户交互,显示省市县三级联动的选择

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    dic = {
        "河北": {
            "石家庄": ["鹿泉""藁城""元氏"],
            "邯郸": ["永年""涉县""磁县"],
        }
        "河南": {
            ...
        }
        "山西": {
            ...
        }
     
    }
     
  • 相关阅读:
    解决winform DataGridView 绑定数字值列排序不对的问题
    C#中向数据库中添加注册新用户,并查询数据库中是否存在同名的用户。
    SQL数据库的脱机与联机操作
    odoo视频教程收集
    odoo10导入导出-转
    草稿-bom- 肥料生产
    freebsd 域名服务器
    freebsd启动报错:My unqualified host name unkown...Sleeping for retry.
    docker-freebsd-20150625
    supervisorctl error
  • 原文地址:https://www.cnblogs.com/Josie-chen/p/8664227.html
Copyright © 2011-2022 走看看