zoukankan      html  css  js  c++  java
  • (三)、python运算符和基本数据类型

    运算符

    1、算数运算:

    2、比较运算:

    3、赋值运算:

    4、逻辑运算:

    5、成员运算:

    基本数据类型

    1.数字

    int(整形)

    # python3里不管数字有多长都叫整形
    # python2里分为整形和长整形

      在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
      在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

      - int
        将字符串转换为数字
        a = "123"
        print(type(a),a)

        b = int(a)
        print(type(b),b)

        num = "0101"
        v = int(num, base=16) #base是进制
        print(v)

      - bit_length
        #当前数字的二进制至少用几位表示
        r = age.bit_length()

    2.字符串

      1) capitalize :首字母大写

        # test = "lYj"
        # v = test.capitalize()
        # print(v)

        def capitalize(self): # real signature unknown; restored from __doc__
            """
            S.capitalize() -> str
            
            Return a capitalized version of S, i.e. make the first character
            have upper case and the rest lower case.
            """
            return ""
    capitalize(self)

       2)所有的变小写,和lower相比 casefold 更牛逼,很多未知的对应关系都变小写

        lower() 只对 ASCII 也就是 'A-Z'有效,但是其它一些语言里面存在小写的情况就没办法了。文档里面举得例子是德语中'ß'的小写是'ss',总结来说,汉语 & 英语环境下面,继续用 lower()没问题;要处理其它语言且存在大小写情况的时候再用casefold()

        # v1 = test.casefold()
        # print(v1)
        # v2 = test.lower()
        # print(v2)

        def casefold(self): # real signature unknown; restored from __doc__
            """
            S.casefold() -> str
            
            Return a version of S suitable for caseless comparisons.
            """
            return ""
    casefold(self)

      3)设置宽度,并将内容居中

        # 20 代指总长度
        # * 空白未知填充,一个字符,可有可无

        # test = "lyj"
        # v = test.center(20,"中")
        # print(v)

        #中中中中中中中中lyj中中中中中中中中中

        #ljust:在右边填充

        # test = "lyj"
        # v = test.ljust(20,"*")
        # print(v)

        #rjust:在左边填充

        # test = "lyj"
        # v = test.rjust(20,"*")
        # print(v)

        # test = "lyj"
        # v = test.zfill(20)
        # print(v)

        #00000000000000000lyj  默认只能用0填充,宽度为20 ,不能选其他字符串

       def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            S.center(width[, fillchar]) -> str
            
            Return S centered in a string of length width. Padding is
            done using the specified fill character (default is a space)
            """
            return ""
    center(self, width, fillchar=None)
        def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            S.ljust(width[, fillchar]) -> str
            
            Return S left-justified in a Unicode string of length width. Padding is
            done using the specified fill character (default is a space).
            """
            return ""
    ljust(self, width, fillchar=None)
        def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            S.rjust(width[, fillchar]) -> str
            
            Return S right-justified in a string of length width. Padding is
            done using the specified fill character (default is a space).
            """
            return ""
    rjust(self, width, fillchar=None)
        def zfill(self, width): # real signature unknown; restored from __doc__
            """
            S.zfill(width) -> str
            
            Pad a numeric string S with zeros on the left, to fill a field
            of the specified width. The string S is never truncated.
            """
            return ""
    zfill(self, width)

      4)count :去字符串中寻找子序列出现的次数,并且可以设置起始和结束的位置

        # test = "aLexalexr"
        # v = test.count('ex')
        # print(v)

        # test = "aLexalexr"
        # v = test.count('ex',5,6)
        # print(v)

        def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.count(sub[, start[, end]]) -> int
            
            Return the number of non-overlapping occurrences of substring sub in
            string S[start:end].  Optional arguments start and end are
            interpreted as in slice notation.
            """
            return 0
    count(self, sub, start=None, end=None)

       5)endswith、startswith :是否以什么什么结尾、开始,返回 True 或者 False

        # test = "liyongjian"
        # v = test.endswith('l')
        # v = test.startswith('l')
        # print(v)
        def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.endswith(suffix[, start[, end]]) -> bool
            
            Return True if S ends with the specified suffix, False otherwise.
            With optional start, test S beginning at that position.
            With optional end, stop comparing S at that position.
            suffix can also be a tuple of strings to try.
            """
            return False
    endswith(self, suffix, start=None, end=None)
        def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.startswith(prefix[, start[, end]]) -> bool
            
            Return True if S starts with the specified prefix, False otherwise.
            With optional start, test S beginning at that position.
            With optional end, stop comparing S at that position.
            prefix can also be a tuple of strings to try.
            """
            return False
    startswith(self, prefix, start=None, end=None)

      6)expandtabs:断句 

        # test1 =  "12345678	9	afag"
        # test2 = "username email password lyj lyj@lyj.com 123 lyj lyj@lyj.com 123 lyj lyj@lyj.com 123 "
        #以6个为一组断句,不足6个用	补全成空格
        # v1 = test1.expandtabs(6)
        #用于打印表格
        # v2 = test2.expandtabs(20)
        # print(v1,len(v1))
        # print(v2)
        def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
            """
            S.expandtabs(tabsize=8) -> str
            
            Return a copy of S where all tab characters are expanded using spaces.
            If tabsize is not given, a tab size of 8 characters is assumed.
            """
            return ""
    expandtabs(self, tabsize=8)

      7)find: 从开始往后找,找到第一个之后,获取其位置。如果返回-1 表示没找到

        # test = "alexalex"
        # #未找到 -1
        # v = test.find('ex',5,7)
        # print(v)
    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.find(sub[, start[, end]]) -> int
            
            Return the lowest index in S where substring sub is found,
            such that sub is contained within S[start:end].  Optional
            arguments start and end are interpreted as in slice notation.
            
            Return -1 on failure.
            """
            return 0
    find(self, sub, start=None, end=None)

      8)index :同 find 一样获取其位置,一般来说用 find 比较好,这个可以忽略掉。如果要找的值不存在于 str 中,会直接报错

        # test = "lyjlyjlyj"
        # v = test.index('xxx')
        # print(v)
    def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.index(sub[, start[, end]]) -> int
            
            Like S.find() but raise ValueError when the substring is not found.
            """
            return 0
    index(self, sub, start=None, end=None)

      9)format:格式化,将一个字符串中的占位符替换为指定的值

        # test = "i am {name}, age {a}"
        # print(test)
        # v = test.format(name='lyj',a=19)
        # print(v)


        #按照位置传递,第一个位置是0
        # test = "i am {0}, age {1}"
        # print(test)
        # v = test.format('lyj',19)
        # print(v)

    def format(self, *args, **kwargs): # known special case of str.format
            """
            S.format(*args, **kwargs) -> str
            
            Return a formatted version of S, using substitutions from args and kwargs.
            The substitutions are identified by braces ('{' and '}').
            """
            pass
    format(self, *args, **kwargs)

      补充:

        # v = "我是:%s;年龄:%s;性别:%s" %( 'lyj',18,'man')
        # print(v)

      10)format_map:格式化,传入的值 {"name": 'lyj', "a": 19}

        # test = "i am {name}, age {a}"
        # v1 = test.format(name='lyj',a=19)
        # v2 = test.format_map({"name":'lyj',"a":19}) #想当于传了一个字典
        # print(v1)
        # print(v2)

        def format_map(self, mapping): # real signature unknown; restored from __doc__
            """
            S.format_map(mapping) -> str
            
            Return a formatted version of S, using substitutions from mapping.
            The substitutions are identified by braces ('{' and '}').
            """
            return ""
    format_map(self, mapping)

       11)isalnum:字符串中只能包含 字母和数字,返回 True 或 False

        # test = "uasfa3151_+"
        # v = test.isalnum()
        # print(v)
        def isalnum(self): # real signature unknown; restored from __doc__
            """
            S.isalnum() -> bool
            
            Return True if all characters in S are alphanumeric
            and there is at least one character in S, False otherwise.
            """
            return False
    isalnum(self)

      12)isalpha:是否是字母,汉字

        # test = "asdg爱国"
        # v = test.isalpha()
        # print(v)
        def isalpha(self): # real signature unknown; restored from __doc__
            """
            S.isalpha() -> bool
            
            Return True if all characters in S are alphabetic
            and there is at least one character in S, False otherwise.
            """
            return False
    isalpha(self)

      13)当前输入是否是数字

        # test = "②"
        # v1 = test.isdecimal() #十进制小数
        # v2 = test.isdigit()
        # print(v1,v2)
        False True
        # test = "二" # 1,②
        # v1 = test.isdecimal() #Unicode数字,,全角数字(双字节) ===》用的最多
        # v2 = test.isdigit() #Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
        # v3 = test.isnumeric() #Unicode数字,全角数字(双字节),罗马数字,汉字数字
        # print(v1,v2,v3)
        def isdecimal(self): # real signature unknown; restored from __doc__
            """
            S.isdecimal() -> bool
            
            Return True if there are only decimal characters in S,
            False otherwise.
            """
            return False
    isdecimal(self)
        def isdigit(self): # real signature unknown; restored from __doc__
            """
            S.isdigit() -> bool
            
            Return True if all characters in S are digits
            and there is at least one character in S, False otherwise.
            """
            return False
    isdigit(self)
    def isnumeric(self): # real signature unknown; restored from __doc__
            """
            S.isnumeric() -> bool
            
            Return True if there are only numeric characters in S,
            False otherwise.
            """
            return False
    isnumeric(self)

      14)isprintable:是否存在不可显示的字符,不存在如下两个字符为 True ,存在为 False

        # 	   制表符
        # 换行
        # test = "oiuas dfkj"
        # v = test.isprintable()
        # print(v)
        def isprintable(self): # real signature unknown; restored from __doc__
            """
            S.isprintable() -> bool
            
            Return True if all characters in S are considered
            printable in repr() or S is empty, False otherwise.
            """
            return False
    isprintable(self)

      15)isspace:判断是否全部是空格 有空格为True

        # test = ""
        # v = test.isspace()
        # print(v)

        def isspace(self): # real signature unknown; restored from __doc__
            """
            S.isspace() -> bool
            
            Return True if all characters in S are whitespace
            and there is at least one character in S, False otherwise.
            """
            return False
    isspace(self)

      16)istitle、title:判断是否是标题,标题是每个首字母都是大写

        # test = "Return True if all cased characters in S are uppercase and there is"
        # v1 = test.istitle()
        # print(v1)
        # v2 = test.title()
        # print(v2)
        # v3 = v2.istitle()
        # print(v3)

        def istitle(self): # real signature unknown; restored from __doc__
            """
            S.istitle() -> bool
            
            Return True if S is a titlecased string and there is at least one
            character in S, i.e. upper- and titlecase characters may only
            follow uncased characters and lowercase characters only cased ones.
            Return False otherwise.
            """
            return False
    istitle(self)
        def title(self): # real signature unknown; restored from __doc__
            """
            S.title() -> str
            
            Return a titlecased version of S, i.e. words start with title case
            characters, all remaining cased characters have lower case.
            """
            return ""
    title(self)

      17)将字符串中的每一个元素按照指定分隔符进行拼接

        # test = "你是风儿我是沙"
        # print(test)
        # t = ' '
        # v1 = t.join(test)
        # v2 = "_".join(test)
        # print(v1)
        # print(v2)
        #join的内部其实就是将字符串做了一个循环
        def join(self, iterable): # real signature unknown; restored from __doc__
            """
            S.join(iterable) -> str
            
            Return a string which is the concatenation of the strings in the
            iterable.  The separator between elements is S.
            """
            return ""
    join(self, iterable)

      18)判断是否全部是大小写 和 转换为大小写 ,网站验证码会都弄成小写比较

        # test = "Lyj"
        # v1 = test.islower()
        # v2 = test.lower()
        # print(v1, v2)

        # test = "Lyj"
        # v1 = test.isupper()
        # v2 = test.upper()
        # print(v1,v2)
        def islower(self): # real signature unknown; restored from __doc__
            """
            S.islower() -> bool
            
            Return True if all cased characters in S are lowercase and there is
            at least one cased character in S, False otherwise.
            """
            return False
    islower(self)
        def lower(self): # real signature unknown; restored from __doc__
            """
            S.lower() -> str
            
            Return a copy of the string S converted to lowercase.
            """
            return ""
    lower(self)
        def isupper(self): # real signature unknown; restored from __doc__
            """
            S.isupper() -> bool
            
            Return True if all cased characters in S are uppercase and there is
            at least one cased character in S, False otherwise.
            """
            return False
    isupper(self)
        def upper(self): # real signature unknown; restored from __doc__
            """
            S.upper() -> str
            
            Return a copy of S converted to uppercase.
            """
            return ""
    upper(self)

      19)移除指定字符串     lstrip从左边  rstrip 从右边 strip从两头删

        # 优先最多匹配
        # test = "xalex"
        # # v = test.lstrip('xa')
        # v = test.rstrip('9lexxexa') #子序列匹配到就删除
        # # v = test.strip('xa')
        # print(v)
        # test.lstrip()
        # test.rstrip()
        # test.strip()
        # 去除左右空白
        # test = " asf af "
        # v = test.lstrip()
        # v = test.rstrip()
        # v = test.strip()
        # print(v)
        # print(test)
        # 去除
        # test = " asf af "
        # v = test.lstrip()
        # v = test.rstrip()
        # v = test.strip()
        # print(v)
        def lstrip(self, chars=None): # real signature unknown; restored from __doc__
            """
            S.lstrip([chars]) -> str
            
            Return a copy of the string S with leading whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            """
            return ""
    lstrip(self, chars=None)
        def rstrip(self, chars=None): # real signature unknown; restored from __doc__
            """
            S.rstrip([chars]) -> str
            
            Return a copy of the string S with trailing whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            """
            return ""
    rstrip(self, chars=None)
        def strip(self, chars=None): # real signature unknown; restored from __doc__
            """
            S.strip([chars]) -> str
            
            Return a copy of the string S with leading and trailing
            whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            """
            return ""
    strip(self, chars=None)

      20)maketrans、translate:对应关系替换,maketrans() 方法用于给 translate() 方法创建字符映射转换表

        # test = "aeiou"
        # test1 = "12345"

        #aeiou 分别对应 12345
        # v = "asidufkasd;fiuadkf;adfkjalsdjf"

        # 对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串,表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。
        # m = str.maketrans("aeiou", "12345") #python3和2不一样
        # new_v = v.translate(m)
        # print(new_v)

        def maketrans(self, *args, **kwargs): # real signature unknown
            """
            Return a translation table usable for str.translate().
            
            If there is only one argument, it must be a dictionary mapping Unicode
            ordinals (integers) or characters to Unicode ordinals, strings or None.
            Character keys will be then converted to ordinals.
            If there are two arguments, they must be strings of equal length, and
            in the resulting dictionary, each character in x will be mapped to the
            character at the same position in y. If there is a third argument, it
            must be a string, whose characters will be mapped to None in the result.
            """
            pass
    maketrans(self, *args, **kwargs)
        def translate(self, table): # real signature unknown; restored from __doc__
            """
            S.translate(table) -> str
            
            Return a copy of the string S in which each character has been mapped
            through the given translation table. The table must implement
            lookup/indexing via __getitem__, for instance a dictionary or list,
            mapping Unicode ordinals to Unicode ordinals, strings, or None. If
            this operation raises LookupError, the character is left untouched.
            Characters mapped to None are deleted.
            """
            return ""
    translate(self, table)

      21)分割为三部分,包含分割的元素

        #('te', 's', 'tasdsddfg')
        # ('testasd', 's', 'ddfg')

        # test = "testasdsddfg"
        # v = test.partition('s')  #从左往右第一个s处分割
        # print(v)
        # v = test.rpartition('s')  #从右往左第一个s处分割
        # print(v)

        def partition(self, sep): # real signature unknown; restored from __doc__
            """
            S.partition(sep) -> (head, sep, tail)
            
            Search for the separator sep in S, and return the part before it,
            the separator itself, and the part after it.  If the separator is not
            found, return S and two empty strings.
            """
            pass
    partition(self, sep)
        def rpartition(self, sep): # real signature unknown; restored from __doc__
            """
            S.rpartition(sep) -> (head, sep, tail)
            
            Search for the separator sep in S, starting at the end of S, and return
            the part before it, the separator itself, and the part after it.  If the
            separator is not found, return two empty strings and S.
            """
            pass
    rpartition(self, sep)

      22)分割为指定个数,不包含分割的元素

        # test = "testasdsddfg"
        # v = test.split('s',2)   #根据s分割,指定分割的个数,匹配的s,就没了;2代表切两刀
        # print(v)
        # v = test.rsplit('s',2)  #从右边开始
        # print(v)

        ['te', 'ta', 'dsddfg']
        ['testa', 'd', 'ddfg']

        def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
            """
            S.split(sep=None, maxsplit=-1) -> list of strings
            
            Return a list of the words in S, using sep as the
            delimiter string.  If maxsplit is given, at most maxsplit
            splits are done. If sep is not specified or is None, any
            whitespace string is a separator and empty strings are
            removed from the result.
            """
            return []
    split(self, sep=None, maxsplit=-1)
        def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
            """
            S.rsplit(sep=None, maxsplit=-1) -> list of strings
            
            Return a list of the words in S, using sep as the
            delimiter string, starting at the end of the string and
            working to the front.  If maxsplit is given, at most maxsplit
            splits are done. If sep is not specified, any whitespace string
            is a separator.
            """
            return []
    rsplit(self, sep=None, maxsplit=-1)

      23)splitlines:分割,只能根据换行进行分割,true,false:是否保留换行符, 按照行(' ', ' ', ')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

        # test = "asdf
    adfasdf
    asdfasdf
    adfasdf"
        # v = test.splitlines(True) #保留
        # # v = test.splitlines(False) #不保留
        # print(v)
        def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
            """
            S.splitlines([keepends]) -> list of strings
            
            Return a list of the lines in S, breaking at line boundaries.
            Line breaks are not included in the resulting list unless keepends
            is given and true.
            """
            return []
    splitlines(self, keepends=None)

      24)以xxx开头,以xx结尾  #检查字符串是否是以 str开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查.

        # test = "backend 1.1.1.1"
        # v1 = test.startswith('a')
        # print(v1)
        # v2 = test.endswith('a')
        # print(v2)
        def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.startswith(prefix[, start[, end]]) -> bool
            
            Return True if S starts with the specified prefix, False otherwise.
            With optional start, test S beginning at that position.
            With optional end, stop comparing S at that position.
            prefix can also be a tuple of strings to try.
            """
            return False
    startswith(self, prefix, start=None, end=None)
        def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.endswith(suffix[, start[, end]]) -> bool
            
            Return True if S ends with the specified suffix, False otherwise.
            With optional start, test S beginning at that position.
            With optional end, stop comparing S at that position.
            suffix can also be a tuple of strings to try.
            """
            return False
    endswith(self, suffix, start=None, end=None)

      25)swapcase:小写转换,互换

        # test = "lYj"
        # v = test.swapcase()
        # print(v)
        def swapcase(self): # real signature unknown; restored from __doc__
            """
            S.swapcase() -> str
            
            Return a copy of S with uppercase characters converted to lowercase
            and vice versa.
            """
            return ""
    swapcase(self)

      26)是否是标识符。标识符必须以字母(大小写均可)或者"_"开头,接下来可以重复0到多次(字母|数字|"_")

        # a = "_123"
        # v = a.isidentifier()
        # print(v)
        def isidentifier(self): # real signature unknown; restored from __doc__
            """
            S.isidentifier() -> bool
            
            Return True if S is a valid identifier according
            to the language definition.
            
            Use keyword.iskeyword() to test for reserved identifiers
            such as "def" and "class".
            """
            return False
    isidentifier(self)

      27)replace:替换

        # test = "alexalexalex"
        # # v = test.replace("ex",'bbb')
        # # print(v)
        # v = test.replace("ex",'bbb',1) #写1 就是第一个 ,写2 就是前两个
        # print(v)
        def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
            """
            S.replace(old, new[, count]) -> str
            
            Return a copy of S with all occurrences of substring
            old replaced by new.  If the optional argument count is
            given, only the first count occurrences are replaced.
            """
            return ""
    replace(self, old, new, count=None)

      字符串中要记住:join #"_".join("afga")、split、find、strip、upper、lower、replace

               索引:

                  # test = "alex"
                  #索引,下标,获取字符串中的某一个字符
                  # v = test[0]
                  # print(v)

               切片:

                  #v = test[0:1]  # 0<=  <1
                  # v = test[0:-1]
                  # print(v)

               获取字符串长度: python3 中是 3. python2 中是 9

                  注意: 其他数据类型也可以用,列表 元祖
                  # test = "李永健"
                  # v = len(test)
                  # print(v)

               for循环:

                  # for 变量名 in 字符串:
                  # 变量名
                  # for item in test:
                  # print(item)
                  # break
                  
                  # for item in test:
                  # continue
                  # print(item)

              range:帮助创建连续的数字range(0,100) 0<= <100,通过设置步长来指定不连续

                 #v = range(100)  #0-99 #在python2中会立即执行出range(100)的结果浪费内存,python3节省内容不会立即执行

                  # test = input(">>>")
                  # for item in range(0,len(test)):
                  # print(item,test[item])
                  
                  差别:
                    python2:
                      range  立即创建
                      xrange  for 循环时候才一个一个创建
                    python3:
                      range   for 循环时候才一个一个创建
                  补充:
                    for i in range(0,100,1):  #正着增
                      print(i)
                    
                    for i in range(100,0,-1):  #倒着减
                      print(i)

    3.列表

    # list 类,可变类型
    # li = [11,22,33,22,44]

    灰魔法:

      1)append:原来值的最后追加

        # 对象..方法(..)    # li对象调用 append 方法
        # li.append(5)
        # li.append("lyj")
        # li.append([1234,2323])
        # print(li)
        返回 ==>  [11, 22, 33, 22, 44, 5, 'lyj', [1234, 2323]]
        def append(self, p_object): # real signature unknown; restored from __doc__
            """ L.append(object) -> None -- append object to end """
            pass
    append(self, p_object)

      2)clear:清空列表

        # li.clear()
        # print(li)
        返回 ==> []
        def clear(self): # real signature unknown; restored from __doc__
            """ L.clear() -> None -- remove all items from L """
            pass
    clear(self)

      3)copy:拷贝,浅拷贝

        # v = li.copy()
        # print(v)
        def copy(self): # real signature unknown; restored from __doc__
            """ L.copy() -> list -- a shallow copy of L """
            return []
    copy(self)

      4)count:计算元素出现的次数

        # li = [11,22,33,22,44]
        # v = li.count(22)
        # print(v)
        返回 ==> 2
        def count(self, value): # real signature unknown; restored from __doc__
            """ L.count(value) -> integer -- return number of occurrences of value """
            return 0
    count(self, value)

      5) extend:  扩展原列表,参数:可迭代对象。  iterable 可迭代的 

        # li = [11,22,33,44]
        # # li.append([9898,"不得了"]) #append是把传入的值当作整体追加到后面 #[11, 22, 33, 44, [9898, '不得了']]
        # # li.extend([9898,"不得了"]) #extend 是把传入的值循环 把每一个值追加进去 #[11, 22, 33, 44, 9898, '不得了']
        # li.extend("不得了")      #[11, 22, 33, 44, '不', '得', '了']
        # print(li)
        def extend(self, iterable): # real signature unknown; restored from __doc__
            """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
            pass
    extend(self, iterable)

      6)index:  根据值去获取当前值索引位置(左边优先),找到了就不找了

        # li = [11,22,33,22,44]
        # v = li.index(22)
        # print(v)
        返回 ==> 1
        def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
            """
            L.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    index(self, value, start=None, stop=None)

      7) insert: 在制定索引位置插入元素

        # li = [11,22,33,22,44]
        # li.insert(0,99)
        # print(li)
        返回 ==> [99, 11, 22, 33, 22, 44]
     def insert(self, index, p_object): # real signature unknown; restored from __doc__
            """ L.insert(index, object) -- insert object before index """
            pass
    insert(self, index, p_object)

      8) pop: 删除某个值(1.指定索引;2.默认最后一个),并获取删除的值

        # li = [11,22,33,22,44]
        # v = li.pop() #默认删除最后一个,获取被删除值
        # 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
        def pop(self, index=None): # real signature unknown; restored from __doc__
            """
            L.pop([index]) -> item -- remove and return item at index (default last).
            Raises IndexError if list is empty or index is out of range.
            """
            pass
    pop(self, index=None)

      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
        def remove(self, value): # real signature unknown; restored from __doc__
            """
            L.remove(value) -> None -- remove first occurrence of value.
            Raises ValueError if the value is not present.
            """
            pass
    remove(self, value)

      10)reverse: 将当前列表进行反转

        # li = [11,22,33,22,44]
        # li.reverse()
        # print(li)
        返回 ==> [44, 22, 33, 22, 11]
        def reverse(self): # real signature unknown; restored from __doc__
            """ L.reverse() -- reverse *IN PLACE* """
            pass
    reverse(self)

      11) sort: 列表的排序

        # li = [11,44,22,33,22]
        # # li.sort()      #正序,返回 ==> [11, 22, 22, 33, 44]
        # # li.sort(reverse=False) #正序,返回 ==> [11, 22, 22, 33, 44]
        # li.sort(reverse=True)   #反序,返回 ==> [44, 33, 22, 22, 11]
        # print(li)
        def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
            """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
            pass
    sort(self, key=None, reverse=False)

    深灰魔法:

      1)列表格式(中括号括起来 ,逗号分割每个元素)
        # list #类,列表
        # li = [1, 12, 9, "age", ["安抚", "庞麦郎"], "alex", True] # 对象通过list类创建的对象,变量名叫li
      2) 列表中可以嵌套任何类型 
        列表中的元素可以是 数字,字符串,列表,布尔值...所有的都能放进去
      3) 索引取值
        # print(li[0])
      4) 切片,切片结果也是列表
        # print(li[3:5])  # 3<=  <5
      5)for 循环
        # li = [11,22,33,22,44]
        # for i in li:
        # print(i)
        返回 ==>
            11
            22
            33
            22
            44
      6) 索引
       修改:
        # li = [11,22,33,22,44]
        # li[1] = 120
        # print(li)  #  返回 ==> [11, 120, 33, 22, 44]
        # li[1] = [11,22,33,44]
        # print(li)  #  返回 ==> [11, [11, 22, 33, 44], 33, 22, 44]

      删除:
        # li = [11,22,33,22,44]
        # del li[1]
        # print(li)  #  返回 ==> [11, 33, 22, 44]
      7) 切片
       修改:
        # li = [11,22,33,22,44]
        # li[1:3] = [120,90]
        # print(li)  #  返回 ==> [11, 120, 90, 22, 44]
       删除:
        # li = [11,22,33,22,44]
        # del li[2:6]
        # print(li)  #  返回 ==> [11, 22]
      8) in 操作
        # li = [1, 12, 9, "age", ["安抚", "庞麦郎"], "alex", True]
        # v = 12 in li
        # print(v)  #  返回 ==> True
      9) 操作
        # li = [1, 12, 9, "age", ["安抚",["19",10], "庞麦郎"], "alex", True]
        # v = li[4][1][0]
        # print(v) # 返回 ==> 19
      10) 转换
       # 字符串转换成列表   li = list("agdagah") ,内部使用for循环
        # s = "asgadgadgdalhjklladfsg"
        # new_li = list(s) #将字符串转换成列表
        # print(new_li)
        返回 ==> ['a', 's', 'g', 'a', 'd', 'g', 'a', 'd', 'g', 'd', 'a', 'l', 'h', 'j', 'k', 'l', 'l', 'a', 'd', 'f', 's', 'g']
     
       # 列表转换成字符串,
        # 需要自己写for 循环一个一个处理: 既有数字又有字符串
        # li = [11,22,33,"123","alex"]
        # # r = str(li)
        # # print(r) #  返回 ==> [11, 22, 33, '123', 'alex']

        # s = ""
        # for i in li:  
        # s += str(i)
        # print(s)    #  返回 ==> 112233123alex
        # 直接使用字符串 join 方法:列表中的元素只有字符串
        # li = ["123","alex"]
        # v = "".join(li)
        # print(v) #  返回 ==> 123alex
    4.元祖(有序、元素不可被修改,不能被增加或者或者删除
    #tuple
    tu = (11,22,33,44)

        # tu.count(22), 获取指定元素在元祖中出现的次数
        def count(self, value): # real signature unknown; restored from __doc__
            """ T.count(value) -> integer -- return number of occurrences of value """
            return 0
    count(self, value)
        # tu.index(22), 根据值去获取当前值索引位置(左边优先),找到了就不找了
        def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
            """
            T.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    index(self, value, start=None, stop=None)

      深灰魔法:

      1)书写格式:

        # tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
        # 一般写元祖的时候多加个逗号,推荐在最后加入逗号,便于区分
        # 元素不可被修改,不能被增加或者或者删除

      2)索引

        # v = tu[0]
        # print(v)

      3)切片

        # v = tu[0:2]
        # print(v)

      4)可以被for循环 ,是可迭代对象

        # for item in tu:
        # print(item)

      5)转换

        # s = "sfsg"
        # li = ["asgda",1231]
        # # tu = (123,123,"asf")
        # tu = ("agda","asf")
        # v = tuple(s)
        # print(v) #  返回 ==> ('s', 'f', 's', 'g')
        
        # v = tuple(li)
        # print(v) #  返回 ==> ('asgda', 1231)
         
        # v = list(tu)
        # print(v) #
      返回 ==> ['agda', 'asf']
         
        # v = "_".join(tu) #tu中没有数字,全是字母的时候可以用join;有数字和字母的时候需要自己写for循环
        # print(v) #  返回 ==> agda_asf

      6)元祖的一级元素不可修改/删除/增加

        # tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
        # # 元祖,有序。tu[0]
        # v = tu[3][0][0]  
        # print(v)   #  返回 ==> 33
        # #元素内的列表可以修改
        # tu[3][0] = 567
        # print(tu)  #  返回 ==> (111, 'alex', (11, 22), [567], True, 33, 44)

    5.字典

    # 字典
    # dict

    # dic = {
    # "k1": 'v1',
    # "k2": 'v2'
    # }

    灰魔法:

      1)clear:清空字典

        # dic = {
        # "k1": 'v1',
        # "k2": 'v2'
        # }
        # dic.clear()
        # print(dic)   #  返回 ==> {}
        def clear(self): # real signature unknown; restored from __doc__
            """ D.clear() -> None.  Remove all items from D. """
            pass
    clear(self)

      2)拷贝,浅拷贝

        # dic = {
        # "k1": 'v1',
        # "k2": 'v2'
        # }
        # a = dic.copy()
        # print(a) #  返回 ==> {'k2': 'v2', 'k1': 'v1'}
        def copy(self): # real signature unknown; restored from __doc__
            """ D.copy() -> a shallow copy of D """
            pass
    copy(self)

      3)fromkeys:根据序列,创建字典,并指定统一的值

        # v1 = dict.fromkeys(["k1",123,"999"])  #创建3个key,值为None
        # v2 = dict.fromkeys(["k1",123,"999"],123)
        # print(v1,' ',v2)
        返回 ==>
        {'999': None, 123: None, 'k1': None}
        {'999': 123, 123: 123, 'k1': 123}
        def fromkeys(*args, **kwargs): # real signature unknown
            """ Returns a new dict with keys from iterable and values equal to value. """
            pass
    fromkeys(*args, **kwargs)

      4) get:根据Key获取值,key不存在时,可以指定默认值(None)

        # dic = {
        # "k1": 'v1',
        # "k2": 'v2'
        # }
        # v = dic['k1'] #传的值不存在 会报错
        # print(v)
        # # v = dic.get('k1')   #传的值不存在,会返回None
        # v = dic.get('k111',1111) #传的值不存在,把1111返给你
        # print(v)
        def get(self, k, d=None): # real signature unknown; restored from __doc__
            """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
            pass
    get(self, k, d=None)

      5) pop、popitem:删除并获取值

        # dic = {
        # "k1": 'v1',
        # "k2": 'v2'
        # }
        # # v = dic.pop('k1') #获取被删除的key的值
        # # v = dic.pop('k111',90 ) #被删除的key不存在的时候,返回一个值
        # k,v = dic.popitem() #随机删
        # print(dic,k,v)
        返回 ==> {'k2': 'v2'} k1 v1 或 {'k1': 'v1'} k2 v2
        def pop(self, k, d=None): # real signature unknown; restored from __doc__
            """
            D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
            If key is not found, d is returned if given, otherwise KeyError is raised
            """
            pass
    pop(self, k, d=None)
        def popitem(self): # real signature unknown; restored from __doc__
            """
            D.popitem() -> (k, v), remove and return some (key, value) pair as a
            2-tuple; but raise KeyError if D is empty.
            """
            pass
    popitem(self)

      6) setdefault:设置值

        # 如果已经存在,不设置,获取当前key对应的值
        # 如果不存在, 设置,获取当前key对应的值
        # dic = {
        # "k1": 'v1',
        # "k2": 'v2'
        # }
        # v = dic.setdefault('k11','123')
        # print(dic,v) #  返回 ==> {'k1': 'v1', 'k2': 'v2', 'k11': '123'} 123
        def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
            """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
            pass
    setdefault(self, k, d=None)

      7) update:更新

        # dic = {
        # "k1": 'v1',
        # "k2": 'v2'
        # }
        # dic.update({'k1': '1111','k3': 123})
        # print(dic) #  返回 ==> {'k1': '1111', 'k3': 123, 'k2': 'v2'}
        #
        # dic.update(k1=123,k3=345,k5="agd")
        # print(dic) #  返回 ==> {'k1': 123, 'k3': 345, 'k2': 'v2', 'k5': 'agd'}
        def update(self, E=None, **F): # known special case of dict.update
            """
            D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
            If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
            If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
            In either case, this is followed by: for k in F:  D[k] = F[k]
            """
            pass
    update(self, E=None, **F)

      8) keys()、values、items:获取 k,v

        #dic = {
        # "k1": 'v1',
        # "k2": 'v2'
        # }
        # for item in dic.values():
        # print(item)
        返回 ==>
            v2
            v1
        # for item in dic.keys():
        # print(item,dic[item])
        返回 ==>
            k2 v2
            k1 v1
        # for k,v in dic.items():
        # print(k,v)
        返回 ==>
            k2 v2
            k1 v1
        def items(self): # real signature unknown; restored from __doc__
            """ D.items() -> a set-like object providing a view on D's items """
            pass
    items(self)
        def keys(self): # real signature unknown; restored from __doc__
            """ D.keys() -> a set-like object providing a view on D's keys """
            pass
    keys(self)
        def values(self): # real signature unknown; restored from __doc__
            """ D.values() -> an object providing a view on D's values """
            pass
    values(self)

    深灰魔法:

      1)基本结构

        # info = {
        # "k1":"v1", #键值对
        # "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)布尔值(1,0)、列表、字典不能作为字典的key

        # True 1 False 0    #key重复的时候,后来赋给键的值将成为键的真实值
        # info = {
        # 1: "agad",
        # "k1": "adga",
        # True: "123",
        # #[11,22]: 123, #不可以
        # (11,22): 123, #可以
        # #{'k1':'v1'}: 123 #不可以
        # }
        # print(info)  #  返回 ==> {1: '123', (11, 22): 123, 'k1': 'adga'}

      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)索引方式找到指定元素

        #info = {
        # "k1":18,
        # 2:True,
        # "k3":[
        # 11,
        # [],
        # (),
        # 22,
        # 33,
        # {
        # "kk1":"vv1",
        # "kk2":"vv2",
        # "kk3":(11,22),
        # }
        # ],
        # "k4":(11,22,33,44)
        # }
        #
        # # v = info['k1']
        # # print(v)
        #
        # # v = info[2]
        # # print(v)
        #
        # v = info["k3"][5]['kk3'][0]
        # print(v)

      6) 字典支持 del 删除

        # info = {
        # "k1":18,
        # 2:True,
        # "k3":[
        # 11,
        # [],
        # (),
        # 22,
        # 33,
        # {
        # "kk1":"vv1",
        # "kk2":"vv2",
        # "kk3":(11,22),
        # }
        # ],
        # "k4":(11,22,33,44)
        # }
        #
        # del info['k3'][5]["kk1"]
        # print(info)

      7) for 循环

        # dict
        # 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)

        # for item in info.keys():
        # print(item)

        # for item in info.values():
        # print(item)

        # for item in info.keys():
        # print(item,info[item])

        # for k,v in info.items():
        # print(k,v)

    6.布尔值

    # 0 1
    # bool()
    # None "" () [] {} 0 ==> False #都是False


    其他:

    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] 


  • 相关阅读:
    Mysql中判断一个点是否落在多边形内
    Linux进阶之环境变量文件/etc/profile、/etc/bashrc、/etc/environment
    gitlab打开group_member页面500错误
    jenkins连接k8s集群
    svn备份迁移
    npm管理nodejs版本
    linux远程执行shell脚本或者python脚本无法获取远程主机的环境变量
    ansible-playbook对服务器安装阿里云日志服务agent--ilogtail
    linux安装Arachni进行web网站扫描
    nginx使用免费ssl证书
  • 原文地址:https://www.cnblogs.com/liyongjian5179/p/9038217.html
Copyright © 2011-2022 走看看