{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" }, "toc": "true" }, "source": [ "# Table of Contents\n", "

1  Python 数据类型
1.1  进制
1.2  整数
1.3  浮点型
1.4  算数运算
1.5  字符串
1.6  元组
1.7  列表
1.8  字典
1.9  集合
1.10  运算
1.10.1  比较运算
1.10.2  赋值运算
1.10.3  逻辑运算
1.10.4  成员运算
1.10.5  身份运算
1.10.6  位运算
1.10.7  运算优先级
1.11  内存指针
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Python 数据类型" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 进制\n", "\n", "- 二进制,01\n", "- 八进制,01234567\n", "- 十进制,0123456789\n", "- 十六进制,012345678910ABCDEF" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" }, "solution2": "hidden", "solution2_first": true }, "source": [ "## 整数\n", "如:18,37,84\n", "\n", "每一个整数都具备如下功能:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "solution2": "hidden" }, "outputs": [], "source": [ "class int(object):\n", " \"\"\"\n", " int(x=0) -> int or long\n", " int(x, base=10) -> int or long\n", " \n", " Convert a number or string to an integer, or return 0 if no arguments\n", " are given. If x is floating point, the conversion truncates towards zero.\n", " If x is outside the integer range, the function returns a long instead.\n", " \n", " If x is not a number or if base is given, then x must be a string or\n", " Unicode object representing an integer literal in the given base. The\n", " literal can be preceded by '+' or '-' and be surrounded by whitespace.\n", " The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to\n", " interpret the base from the string as an integer literal.\n", " >>> int('0b100', base=0)\n", " \"\"\"\n", " def bit_length(self): \n", " \"\"\" 返回表示该数字的时占用的最少位数 \"\"\"\n", " \"\"\"\n", " int.bit_length() -> int\n", " \n", " Number of bits necessary to represent self in binary.\n", " >>> bin(37)\n", " '0b100101'\n", " >>> (37).bit_length()\n", " \"\"\"\n", " return 0\n", "\n", " def conjugate(self, *args, **kwargs): # real signature unknown\n", " \"\"\" 返回该复数的共轭复数 \"\"\"\n", " \"\"\" Returns self, the complex conjugate of any int. \"\"\"\n", " pass\n", "\n", " def __abs__(self):\n", " \"\"\" 返回绝对值 \"\"\"\n", " \"\"\" x.__abs__() <==> abs(x) \"\"\"\n", " pass\n", "\n", " def __add__(self, y):\n", " \"\"\" x.__add__(y) <==> x+y \"\"\"\n", " pass\n", "\n", " def __and__(self, y):\n", " \"\"\" x.__and__(y) <==> x&y \"\"\"\n", " pass\n", "\n", " def __cmp__(self, y): \n", " \"\"\" 比较两个数大小 \"\"\"\n", " \"\"\" x.__cmp__(y) <==> cmp(x,y) \"\"\"\n", " pass\n", "\n", " def __coerce__(self, y):\n", " \"\"\" 强制生成一个元组 \"\"\" \n", " \"\"\" x.__coerce__(y) <==> coerce(x, y) \"\"\"\n", " pass\n", "\n", " def __divmod__(self, y): \n", " \"\"\" 相除,得到商和余数组成的元组 \"\"\" \n", " \"\"\" x.__divmod__(y) <==> divmod(x, y) \"\"\"\n", " pass\n", "\n", " def __div__(self, y): \n", " \"\"\" x.__div__(y) <==> x/y \"\"\"\n", " pass\n", "\n", " def __float__(self): \n", " \"\"\" 转换为浮点类型 \"\"\" \n", " \"\"\" x.__float__() <==> float(x) \"\"\"\n", " pass\n", "\n", " def __floordiv__(self, y): \n", " \"\"\" x.__floordiv__(y) <==> x//y \"\"\"\n", " pass\n", "\n", " def __format__(self, *args, **kwargs): # real signature unknown\n", " pass\n", "\n", " def __getattribute__(self, name): \n", " \"\"\" x.__getattribute__('name') <==> x.name \"\"\"\n", " pass\n", "\n", " def __getnewargs__(self, *args, **kwargs): # real signature unknown\n", " \"\"\" 内部调用 __new__方法或创建对象时传入参数使用 \"\"\" \n", " pass\n", "\n", " def __hash__(self): \n", " \"\"\"如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。\"\"\"\n", " \"\"\" x.__hash__() <==> hash(x) \"\"\"\n", " pass\n", "\n", " def __hex__(self): \n", " \"\"\" 返回当前数的 十六进制 表示 \"\"\" \n", " \"\"\" x.__hex__() <==> hex(x) \"\"\"\n", " pass\n", "\n", " def __index__(self): \n", " \"\"\" 用于切片,数字无意义 \"\"\"\n", " \"\"\" x[y:z] <==> x[y.__index__():z.__index__()] \"\"\"\n", " pass\n", "\n", " def __init__(self, x, base=10): # known special case of int.__init__\n", " \"\"\" 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 \"\"\" \n", " \"\"\"\n", " int(x=0) -> int or long\n", " int(x, base=10) -> int or long\n", " \n", " Convert a number or string to an integer, or return 0 if no arguments\n", " are given. If x is floating point, the conversion truncates towards zero.\n", " If x is outside the integer range, the function returns a long instead.\n", " \n", " If x is not a number or if base is given, then x must be a string or\n", " Unicode object representing an integer literal in the given base. The\n", " literal can be preceded by '+' or '-' and be surrounded by whitespace.\n", " The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to\n", " interpret the base from the string as an integer literal.\n", " >>> int('0b100', base=0)\n", " # (copied from class doc)\n", " \"\"\"\n", " pass\n", "\n", " def __int__(self): \n", " \"\"\" 转换为整数 \"\"\" \n", " \"\"\" x.__int__() <==> int(x) \"\"\"\n", " pass\n", "\n", " def __invert__(self): \n", " \"\"\" x.__invert__() <==> ~x \"\"\"\n", " pass\n", "\n", " def __long__(self): \n", " \"\"\" 转换为长整数 \"\"\" \n", " \"\"\" x.__long__() <==> long(x) \"\"\"\n", " pass\n", "\n", " def __lshift__(self, y): \n", " \"\"\" x.__lshift__(y) <==> x< x%y \"\"\"\n", " pass\n", "\n", " def __mul__(self, y): \n", " \"\"\" x.__mul__(y) <==> x*y \"\"\"\n", " pass\n", "\n", " def __neg__(self): \n", " \"\"\" x.__neg__() <==> -x \"\"\"\n", " pass\n", "\n", " @staticmethod # known case of __new__\n", " def __new__(S, *more): \n", " \"\"\" T.__new__(S, ...) -> a new object with type S, a subtype of T \"\"\"\n", " pass\n", "\n", " def __nonzero__(self): \n", " \"\"\" x.__nonzero__() <==> x != 0 \"\"\"\n", " pass\n", "\n", " def __oct__(self): \n", " \"\"\" 返回改值的 八进制 表示 \"\"\" \n", " \"\"\" x.__oct__() <==> oct(x) \"\"\"\n", " pass\n", "\n", " def __or__(self, y): \n", " \"\"\" x.__or__(y) <==> x|y \"\"\"\n", " pass\n", "\n", " def __pos__(self): \n", " \"\"\" x.__pos__() <==> +x \"\"\"\n", " pass\n", "\n", " def __pow__(self, y, z=None): \n", " \"\"\" 幂,次方 \"\"\" \n", " \"\"\" x.__pow__(y[, z]) <==> pow(x, y[, z]) \"\"\"\n", " pass\n", "\n", " def __radd__(self, y): \n", " \"\"\" x.__radd__(y) <==> y+x \"\"\"\n", " pass\n", "\n", " def __rand__(self, y): \n", " \"\"\" x.__rand__(y) <==> y&x \"\"\"\n", " pass\n", "\n", " def __rdivmod__(self, y): \n", " \"\"\" x.__rdivmod__(y) <==> divmod(y, x) \"\"\"\n", " pass\n", "\n", " def __rdiv__(self, y): \n", " \"\"\" x.__rdiv__(y) <==> y/x \"\"\"\n", " pass\n", "\n", " def __repr__(self): \n", " \"\"\"转化为解释器可读取的形式 \"\"\"\n", " \"\"\" x.__repr__() <==> repr(x) \"\"\"\n", " pass\n", "\n", " def __str__(self): \n", " \"\"\"转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式\"\"\"\n", " \"\"\" x.__str__() <==> str(x) \"\"\"\n", " pass\n", "\n", " def __rfloordiv__(self, y): \n", " \"\"\" x.__rfloordiv__(y) <==> y//x \"\"\"\n", " pass\n", "\n", " def __rlshift__(self, y): \n", " \"\"\" x.__rlshift__(y) <==> y< y%x \"\"\"\n", " pass\n", "\n", " def __rmul__(self, y): \n", " \"\"\" x.__rmul__(y) <==> y*x \"\"\"\n", " pass\n", "\n", " def __ror__(self, y): \n", " \"\"\" x.__ror__(y) <==> y|x \"\"\"\n", " pass\n", "\n", " def __rpow__(self, x, z=None): \n", " \"\"\" y.__rpow__(x[, z]) <==> pow(x, y[, z]) \"\"\"\n", " pass\n", "\n", " def __rrshift__(self, y): \n", " \"\"\" x.__rrshift__(y) <==> y>>x \"\"\"\n", " pass\n", "\n", " def __rshift__(self, y): \n", " \"\"\" x.__rshift__(y) <==> x>>y \"\"\"\n", " pass\n", "\n", " def __rsub__(self, y): \n", " \"\"\" x.__rsub__(y) <==> y-x \"\"\"\n", " pass\n", "\n", " def __rtruediv__(self, y): \n", " \"\"\" x.__rtruediv__(y) <==> y/x \"\"\"\n", " pass\n", "\n", " def __rxor__(self, y): \n", " \"\"\" x.__rxor__(y) <==> y^x \"\"\"\n", " pass\n", "\n", " def __sub__(self, y): \n", " \"\"\" x.__sub__(y) <==> x-y \"\"\"\n", " pass\n", "\n", " def __truediv__(self, y): \n", " \"\"\" x.__truediv__(y) <==> x/y \"\"\"\n", " pass\n", "\n", " def __trunc__(self, *args, **kwargs): \n", " \"\"\" 返回数值被截取为整形的值,在整形中无意义 \"\"\"\n", " pass\n", "\n", " def __xor__(self, y): \n", " \"\"\" x.__xor__(y) <==> x^y \"\"\"\n", " pass\n", "\n", " denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default\n", " \"\"\" 分母 = 1 \"\"\"\n", " \"\"\"the denominator of a rational number in lowest terms\"\"\"\n", "\n", " imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default\n", " \"\"\" 虚数,无意义 \"\"\"\n", " \"\"\"the imaginary part of a complex number\"\"\"\n", "\n", " numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default\n", " \"\"\" 分子 = 数字大小 \"\"\"\n", " \"\"\"the numerator of a rational number in lowest terms\"\"\"\n", "\n", " real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default\n", " \"\"\" 实属,无意义 \"\"\"\n", " \"\"\"the real part of a complex number\"\"\"\n", "\n", "int" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" }, "solution2": "hidden", "solution2_first": true }, "source": [ "## 浮点型\n", "\n", "如:3.14,2.88\n", "\n", "每个浮点型都具备如下功能:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "solution2": "hidden" }, "outputs": [], "source": [ "class float(object):\n", " \"\"\"\n", " float(x) -> floating point number\n", " \n", " Convert a string or number to a floating point number, if possible.\n", " \"\"\"\n", " def as_integer_ratio(self): \n", " \"\"\" 获取改值的最简比 \"\"\"\n", " \"\"\"\n", " float.as_integer_ratio() -> (int, int)\n", "\n", " Return a pair of integers, whose ratio is exactly equal to the original\n", " float and with a positive denominator.\n", " Raise OverflowError on infinities and a ValueError on NaNs.\n", "\n", " >>> (10.0).as_integer_ratio()\n", " (10, 1)\n", " >>> (0.0).as_integer_ratio()\n", " (0, 1)\n", " >>> (-.25).as_integer_ratio()\n", " (-1, 4)\n", " \"\"\"\n", " pass\n", "\n", " def conjugate(self, *args, **kwargs): # real signature unknown\n", " \"\"\" Return self, the complex conjugate of any float. \"\"\"\n", " pass\n", "\n", " def fromhex(self, string): \n", " \"\"\" 将十六进制字符串转换成浮点型 \"\"\"\n", " \"\"\"\n", " float.fromhex(string) -> float\n", " \n", " Create a floating-point number from a hexadecimal string.\n", " >>> float.fromhex('0x1.ffffp10')\n", " 2047.984375\n", " >>> float.fromhex('-0x1p-1074')\n", " -4.9406564584124654e-324\n", " \"\"\"\n", " return 0.0\n", "\n", " def hex(self): \n", " \"\"\" 返回当前值的 16 进制表示 \"\"\"\n", " \"\"\"\n", " float.hex() -> string\n", " \n", " Return a hexadecimal representation of a floating-point number.\n", " >>> (-0.1).hex()\n", " '-0x1.999999999999ap-4'\n", " >>> 3.14159.hex()\n", " '0x1.921f9f01b866ep+1'\n", " \"\"\"\n", " return \"\"\n", "\n", " def is_integer(self, *args, **kwargs): # real signature unknown\n", " \"\"\" Return True if the float is an integer. \"\"\"\n", " pass\n", "\n", " def __abs__(self): \n", " \"\"\" x.__abs__() <==> abs(x) \"\"\"\n", " pass\n", "\n", " def __add__(self, y): \n", " \"\"\" x.__add__(y) <==> x+y \"\"\"\n", " pass\n", "\n", " def __coerce__(self, y): \n", " \"\"\" x.__coerce__(y) <==> coerce(x, y) \"\"\"\n", " pass\n", "\n", " def __divmod__(self, y): \n", " \"\"\" x.__divmod__(y) <==> divmod(x, y) \"\"\"\n", " pass\n", "\n", " def __div__(self, y): \n", " \"\"\" x.__div__(y) <==> x/y \"\"\"\n", " pass\n", "\n", " def __eq__(self, y): \n", " \"\"\" x.__eq__(y) <==> x==y \"\"\"\n", " pass\n", "\n", " def __float__(self): \n", " \"\"\" x.__float__() <==> float(x) \"\"\"\n", " pass\n", "\n", " def __floordiv__(self, y): \n", " \"\"\" x.__floordiv__(y) <==> x//y \"\"\"\n", " pass\n", "\n", " def __format__(self, format_spec): \n", " \"\"\"\n", " float.__format__(format_spec) -> string\n", " \n", " Formats the float according to format_spec.\n", " \"\"\"\n", " return \"\"\n", "\n", " def __getattribute__(self, name): \n", " \"\"\" x.__getattribute__('name') <==> x.name \"\"\"\n", " pass\n", "\n", " def __getformat__(self, typestr): \n", " \"\"\"\n", " float.__getformat__(typestr) -> string\n", " \n", " You probably don't want to use this function. It exists mainly to be\n", " used in Python's test suite.\n", " \n", " typestr must be 'double' or 'float'. This function returns whichever of\n", " 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n", " format of floating point numbers used by the C type named by typestr.\n", " \"\"\"\n", " return \"\"\n", "\n", " def __getnewargs__(self, *args, **kwargs): # real signature unknown\n", " pass\n", "\n", " def __ge__(self, y): \n", " \"\"\" x.__ge__(y) <==> x>=y \"\"\"\n", " pass\n", "\n", " def __gt__(self, y): \n", " \"\"\" x.__gt__(y) <==> x>y \"\"\"\n", " pass\n", "\n", " def __hash__(self): \n", " \"\"\" x.__hash__() <==> hash(x) \"\"\"\n", " pass\n", "\n", " def __init__(self, x): \n", " pass\n", "\n", " def __int__(self): \n", " \"\"\" x.__int__() <==> int(x) \"\"\"\n", " pass\n", "\n", " def __le__(self, y): \n", " \"\"\" x.__le__(y) <==> x<=y \"\"\"\n", " pass\n", "\n", " def __long__(self): \n", " \"\"\" x.__long__() <==> long(x) \"\"\"\n", " pass\n", "\n", " def __lt__(self, y): \n", " \"\"\" x.__lt__(y) <==> x x%y \"\"\"\n", " pass\n", "\n", " def __mul__(self, y): \n", " \"\"\" x.__mul__(y) <==> x*y \"\"\"\n", " pass\n", "\n", " def __neg__(self): \n", " \"\"\" x.__neg__() <==> -x \"\"\"\n", " pass\n", "\n", " @staticmethod # known case of __new__\n", " def __new__(S, *more): \n", " \"\"\" T.__new__(S, ...) -> a new object with type S, a subtype of T \"\"\"\n", " pass\n", "\n", " def __ne__(self, y): \n", " \"\"\" x.__ne__(y) <==> x!=y \"\"\"\n", " pass\n", "\n", " def __nonzero__(self): \n", " \"\"\" x.__nonzero__() <==> x != 0 \"\"\"\n", " pass\n", "\n", " def __pos__(self): \n", " \"\"\" x.__pos__() <==> +x \"\"\"\n", " pass\n", "\n", " def __pow__(self, y, z=None): \n", " \"\"\" x.__pow__(y[, z]) <==> pow(x, y[, z]) \"\"\"\n", " pass\n", "\n", " def __radd__(self, y): \n", " \"\"\" x.__radd__(y) <==> y+x \"\"\"\n", " pass\n", "\n", " def __rdivmod__(self, y): \n", " \"\"\" x.__rdivmod__(y) <==> divmod(y, x) \"\"\"\n", " pass\n", "\n", " def __rdiv__(self, y): \n", " \"\"\" x.__rdiv__(y) <==> y/x \"\"\"\n", " pass\n", "\n", " def __repr__(self): \n", " \"\"\" x.__repr__() <==> repr(x) \"\"\"\n", " pass\n", "\n", " def __rfloordiv__(self, y): \n", " \"\"\" x.__rfloordiv__(y) <==> y//x \"\"\"\n", " pass\n", "\n", " def __rmod__(self, y): \n", " \"\"\" x.__rmod__(y) <==> y%x \"\"\"\n", " pass\n", "\n", " def __rmul__(self, y): \n", " \"\"\" x.__rmul__(y) <==> y*x \"\"\"\n", " pass\n", "\n", " def __rpow__(self, x, z=None): \n", " \"\"\" y.__rpow__(x[, z]) <==> pow(x, y[, z]) \"\"\"\n", " pass\n", "\n", " def __rsub__(self, y): \n", " \"\"\" x.__rsub__(y) <==> y-x \"\"\"\n", " pass\n", "\n", " def __rtruediv__(self, y): \n", " \"\"\" x.__rtruediv__(y) <==> y/x \"\"\"\n", " pass\n", "\n", " def __setformat__(self, typestr, fmt): \n", " \"\"\"\n", " float.__setformat__(typestr, fmt) -> None\n", " \n", " You probably don't want to use this function. It exists mainly to be\n", " used in Python's test suite.\n", " \n", " typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n", " 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n", " one of the latter two if it appears to match the underlying C reality.\n", " \n", " Override the automatic determination of C-level floating point type.\n", " This affects how floats are converted to and from binary strings.\n", " \"\"\"\n", " pass\n", "\n", " def __str__(self): \n", " \"\"\" x.__str__() <==> str(x) \"\"\"\n", " pass\n", "\n", " def __sub__(self, y): \n", " \"\"\" x.__sub__(y) <==> x-y \"\"\"\n", " pass\n", "\n", " def __truediv__(self, y): \n", " \"\"\" x.__truediv__(y) <==> x/y \"\"\"\n", " pass\n", "\n", " def __trunc__(self, *args, **kwargs): # real signature unknown\n", " \"\"\" Return the Integral closest to x between 0 and x. \"\"\"\n", " pass\n", "\n", " imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default\n", " \"\"\"the imaginary part of a complex number\"\"\"\n", "\n", " real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default\n", " \"\"\"the real part of a complex number\"\"\"\n", "\n", "float\n", "\n", "float" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## 算数运算\n", "\n", "![数学运算](数学运算.png)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "-10" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "200" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "2.0" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "0" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "100000000000000000000" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "4" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "4.0" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 10\n", "b = 20\n", "\n", "a + b\n", "a - b\n", "a * b\n", "b / a\n", "b % a\n", "a ** b\n", "9 // 2\n", "9.0 // 2.0" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## 字符串\n", "\n", "一个有序的字符的集合,用来存储和表现文本的信息。\n", "\n", "**字符串表达形式:**" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "''" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 空字符串\n", "s = ''\n", "s\n", "s = \"\"\n", "s" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "what's you name?\n", "my name is \"liangxiansen\"\n" ] } ], "source": [ "# 字符串中包含引号\n", "s1 = \"what's you name?\"\n", "s2 = 'my name is \"liangxiansen\"'\n", "\n", "print(s1, s2, sep='\\n')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Infomation of user liangxiansen:\n", "-------------------\n", "Name: liangxiansen\n", "Age : 12\n", "Job : Programmer\n", "---------End-------\n", "\n" ] } ], "source": [ "# 三重引号字符串块\n", "\n", "s3 = \"\"\"\n", "Infomation of user liangxiansen:\n", "-------------------\n", "Name: liangxiansen\n", "Age : 12\n", "Job : Programmer\n", "---------End-------\n", "\"\"\"\n", "\n", "print(s3)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "'liangxiansen \\\\n'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Raw字符串,可以对字符串中的特殊字符转义\n", "s4 = r'liangxiansen \\n'\n", "s4" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'liangxiansen'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Unicode 字符串\n", "s5 = u'liangxiansen'\n", "s5" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "b'liangxiansen'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字节字符串\n", "s6 = b'liangxiansen'\n", "s6" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" }, "solution2": "hidden", "solution2_first": true }, "source": [ "**字符串操作:**\n", "\n", "每个字符串都支持下面操作:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "solution2": "hidden" }, "outputs": [], "source": [ "class str(basestring):\n", " \"\"\"\n", " str(object='') -> string\n", " \n", " Return a nice string representation of the object.\n", " If the argument is a string, the return value is the same object.\n", " \"\"\"\n", " def capitalize(self): \n", " \"\"\" 首字母变大写 \"\"\"\n", " \"\"\"\n", " S.capitalize() -> string\n", " \n", " Return a copy of the string S with only its first character\n", " capitalized.\n", " \"\"\"\n", " return \"\"\n", "\n", " def center(self, width, fillchar=None): \n", " \"\"\" 内容居中,width:总长度;fillchar:空白处填充内容,默认无 \"\"\"\n", " \"\"\"\n", " S.center(width[, fillchar]) -> string\n", " \n", " Return S centered in a string of length width. Padding is\n", " done using the specified fill character (default is a space)\n", " \"\"\"\n", " return \"\"\n", "\n", " def count(self, sub, start=None, end=None): \n", " \"\"\" 子序列个数 \"\"\"\n", " \"\"\"\n", " S.count(sub[, start[, end]]) -> int\n", " \n", " Return the number of non-overlapping occurrences of substring sub in\n", " string S[start:end]. Optional arguments start and end are interpreted\n", " as in slice notation.\n", " \"\"\"\n", " return 0\n", "\n", " def decode(self, encoding=None, errors=None): \n", " \"\"\" 解码 \"\"\"\n", " \"\"\"\n", " S.decode([encoding[,errors]]) -> object\n", " \n", " Decodes S using the codec registered for encoding. encoding defaults\n", " to the default encoding. errors may be given to set a different error\n", " handling scheme. Default is 'strict' meaning that encoding errors raise\n", " a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n", " as well as any other name registered with codecs.register_error that is\n", " able to handle UnicodeDecodeErrors.\n", " \"\"\"\n", " return object()\n", "\n", " def encode(self, encoding=None, errors=None): \n", " \"\"\" 编码,针对unicode \"\"\"\n", " \"\"\"\n", " S.encode([encoding[,errors]]) -> object\n", " \n", " Encodes S using the codec registered for encoding. encoding defaults\n", " to the default encoding. errors may be given to set a different error\n", " handling scheme. Default is 'strict' meaning that encoding errors raise\n", " a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n", " 'xmlcharrefreplace' as well as any other name registered with\n", " codecs.register_error that is able to handle UnicodeEncodeErrors.\n", " \"\"\"\n", " return object()\n", "\n", " def endswith(self, suffix, start=None, end=None): \n", " \"\"\" 是否以 xxx 结束 \"\"\"\n", " \"\"\"\n", " S.endswith(suffix[, start[, end]]) -> bool\n", " \n", " Return True if S ends with the specified suffix, False otherwise.\n", " With optional start, test S beginning at that position.\n", " With optional end, stop comparing S at that position.\n", " suffix can also be a tuple of strings to try.\n", " \"\"\"\n", " return False\n", "\n", " def expandtabs(self, tabsize=None): \n", " \"\"\" 将tab转换成空格,默认一个tab转换成8个空格 \"\"\"\n", " \"\"\"\n", " S.expandtabs([tabsize]) -> string\n", " \n", " Return a copy of S where all tab characters are expanded using spaces.\n", " If tabsize is not given, a tab size of 8 characters is assumed.\n", " \"\"\"\n", " return \"\"\n", "\n", " def find(self, sub, start=None, end=None): \n", " \"\"\" 寻找子序列位置,如果没找到,则异常 \"\"\"\n", " \"\"\"\n", " S.find(sub [,start [,end]]) -> int\n", " \n", " Return the lowest index in S where substring sub is found,\n", " such that sub is contained within S[start:end]. Optional\n", " arguments start and end are interpreted as in slice notation.\n", " \n", " Return -1 on failure.\n", " \"\"\"\n", " return 0\n", "\n", " def format(*args, **kwargs): # known special case of str.format\n", " \"\"\" 字符串格式化,动态参数,将函数式编程时细说 \"\"\"\n", " \"\"\"\n", " S.format(*args, **kwargs) -> string\n", " \n", " Return a formatted version of S, using substitutions from args and kwargs.\n", " The substitutions are identified by braces ('{' and '}').\n", " \"\"\"\n", " pass\n", "\n", " def index(self, sub, start=None, end=None): \n", " \"\"\" 子序列位置,如果没找到,则返回-1 \"\"\"\n", " S.index(sub [,start [,end]]) -> int\n", " \n", " Like S.find() but raise ValueError when the substring is not found.\n", " \"\"\"\n", " return 0\n", "\n", " def isalnum(self): \n", " \"\"\" 是否是字母和数字 \"\"\"\n", " \"\"\"\n", " S.isalnum() -> bool\n", " \n", " Return True if all characters in S are alphanumeric\n", " and there is at least one character in S, False otherwise.\n", " \"\"\"\n", " return False\n", "\n", " def isalpha(self): \n", " \"\"\" 是否是字母 \"\"\"\n", " \"\"\"\n", " S.isalpha() -> bool\n", " \n", " Return True if all characters in S are alphabetic\n", " and there is at least one character in S, False otherwise.\n", " \"\"\"\n", " return False\n", "\n", " def isdigit(self): \n", " \"\"\" 是否是数字 \"\"\"\n", " \"\"\"\n", " S.isdigit() -> bool\n", " \n", " Return True if all characters in S are digits\n", " and there is at least one character in S, False otherwise.\n", " \"\"\"\n", " return False\n", "\n", " def islower(self): \n", " \"\"\" 是否小写 \"\"\"\n", " \"\"\"\n", " S.islower() -> bool\n", " \n", " Return True if all cased characters in S are lowercase and there is\n", " at least one cased character in S, False otherwise.\n", " \"\"\"\n", " return False\n", "\n", " def isspace(self): \n", " \"\"\"\n", " S.isspace() -> bool\n", " \n", " Return True if all characters in S are whitespace\n", " and there is at least one character in S, False otherwise.\n", " \"\"\"\n", " return False\n", "\n", " def istitle(self): \n", " \"\"\"\n", " S.istitle() -> bool\n", " \n", " Return True if S is a titlecased string and there is at least one\n", " character in S, i.e. uppercase characters may only follow uncased\n", " characters and lowercase characters only cased ones. Return False\n", " otherwise.\n", " \"\"\"\n", " return False\n", "\n", " def isupper(self): \n", " \"\"\"\n", " S.isupper() -> bool\n", " \n", " Return True if all cased characters in S are uppercase and there is\n", " at least one cased character in S, False otherwise.\n", " \"\"\"\n", " return False\n", "\n", " def join(self, iterable): \n", " \"\"\" 连接 \"\"\"\n", " \"\"\"\n", " S.join(iterable) -> string\n", " \n", " Return a string which is the concatenation of the strings in the\n", " iterable. The separator between elements is S.\n", " \"\"\"\n", " return \"\"\n", "\n", " def ljust(self, width, fillchar=None): \n", " \"\"\" 内容左对齐,右侧填充 \"\"\"\n", " \"\"\"\n", " S.ljust(width[, fillchar]) -> string\n", " \n", " Return S left-justified in a string of length width. Padding is\n", " done using the specified fill character (default is a space).\n", " \"\"\"\n", " return \"\"\n", "\n", " def lower(self): \n", " \"\"\" 变小写 \"\"\"\n", " \"\"\"\n", " S.lower() -> string\n", " \n", " Return a copy of the string S converted to lowercase.\n", " \"\"\"\n", " return \"\"\n", "\n", " def lstrip(self, chars=None): \n", " \"\"\" 移除左侧空白 \"\"\"\n", " \"\"\"\n", " S.lstrip([chars]) -> string or unicode\n", " \n", " Return a copy of the string S with leading whitespace removed.\n", " If chars is given and not None, remove characters in chars instead.\n", " If chars is unicode, S will be converted to unicode before stripping\n", " \"\"\"\n", " return \"\"\n", "\n", " def partition(self, sep): \n", " \"\"\" 分割,前,中,后三部分 \"\"\"\n", " \"\"\"\n", " S.partition(sep) -> (head, sep, tail)\n", " \n", " Search for the separator sep in S, and return the part before it,\n", " the separator itself, and the part after it. If the separator is not\n", " found, return S and two empty strings.\n", " \"\"\"\n", " pass\n", "\n", " def replace(self, old, new, count=None): \n", " \"\"\" 替换 \"\"\"\n", " \"\"\"\n", " S.replace(old, new[, count]) -> string\n", " \n", " Return a copy of string S with all occurrences of substring\n", " old replaced by new. If the optional argument count is\n", " given, only the first count occurrences are replaced.\n", " \"\"\"\n", " return \"\"\n", "\n", " def rfind(self, sub, start=None, end=None): \n", " \"\"\"\n", " S.rfind(sub [,start [,end]]) -> int\n", " \n", " Return the highest index in S where substring sub is found,\n", " such that sub is contained within S[start:end]. Optional\n", " arguments start and end are interpreted as in slice notation.\n", " \n", " Return -1 on failure.\n", " \"\"\"\n", " return 0\n", "\n", " def rindex(self, sub, start=None, end=None): \n", " \"\"\"\n", " S.rindex(sub [,start [,end]]) -> int\n", " \n", " Like S.rfind() but raise ValueError when the substring is not found.\n", " \"\"\"\n", " return 0\n", "\n", " def rjust(self, width, fillchar=None): \n", " \"\"\"\n", " S.rjust(width[, fillchar]) -> string\n", " \n", " Return S right-justified in a string of length width. Padding is\n", " done using the specified fill character (default is a space)\n", " \"\"\"\n", " return \"\"\n", "\n", " def rpartition(self, sep): \n", " \"\"\"\n", " S.rpartition(sep) -> (head, sep, tail)\n", " \n", " Search for the separator sep in S, starting at the end of S, and return\n", " the part before it, the separator itself, and the part after it. If the\n", " separator is not found, return two empty strings and S.\n", " \"\"\"\n", " pass\n", "\n", " def rsplit(self, sep=None, maxsplit=None): \n", " \"\"\"\n", " S.rsplit([sep [,maxsplit]]) -> list of strings\n", " \n", " Return a list of the words in the string S, using sep as the\n", " delimiter string, starting at the end of the string and working\n", " to the front. If maxsplit is given, at most maxsplit splits are\n", " done. If sep is not specified or is None, any whitespace string\n", " is a separator.\n", " \"\"\"\n", " return []\n", "\n", " def rstrip(self, chars=None): \n", " \"\"\"\n", " S.rstrip([chars]) -> string or unicode\n", " \n", " Return a copy of the string S with trailing whitespace removed.\n", " If chars is given and not None, remove characters in chars instead.\n", " If chars is unicode, S will be converted to unicode before stripping\n", " \"\"\"\n", " return \"\"\n", "\n", " def split(self, sep=None, maxsplit=None): \n", " \"\"\" 分割, maxsplit最多分割几次 \"\"\"\n", " \"\"\"\n", " S.split([sep [,maxsplit]]) -> list of strings\n", " \n", " Return a list of the words in the string S, using sep as the\n", " delimiter string. If maxsplit is given, at most maxsplit\n", " splits are done. If sep is not specified or is None, any\n", " whitespace string is a separator and empty strings are removed\n", " from the result.\n", " \"\"\"\n", " return []\n", "\n", " def splitlines(self, keepends=False): \n", " \"\"\" 根据换行分割 \"\"\"\n", " \"\"\"\n", " S.splitlines(keepends=False) -> list of strings\n", " \n", " Return a list of the lines in S, breaking at line boundaries.\n", " Line breaks are not included in the resulting list unless keepends\n", " is given and true.\n", " \"\"\"\n", " return []\n", "\n", " def startswith(self, prefix, start=None, end=None): \n", " \"\"\" 是否起始 \"\"\"\n", " \"\"\"\n", " S.startswith(prefix[, start[, end]]) -> bool\n", " \n", " Return True if S starts with the specified prefix, False otherwise.\n", " With optional start, test S beginning at that position.\n", " With optional end, stop comparing S at that position.\n", " prefix can also be a tuple of strings to try.\n", " \"\"\"\n", " return False\n", "\n", " def strip(self, chars=None): \n", " \"\"\" 移除两段空白 \"\"\"\n", " \"\"\"\n", " S.strip([chars]) -> string or unicode\n", " \n", " Return a copy of the string S with leading and trailing\n", " whitespace removed.\n", " If chars is given and not None, remove characters in chars instead.\n", " If chars is unicode, S will be converted to unicode before stripping\n", " \"\"\"\n", " return \"\"\n", "\n", " def swapcase(self): \n", " \"\"\" 大写变小写,小写变大写 \"\"\"\n", " \"\"\"\n", " S.swapcase() -> string\n", " \n", " Return a copy of the string S with uppercase characters\n", " converted to lowercase and vice versa.\n", " \"\"\"\n", " return \"\"\n", "\n", " def title(self): \n", " \"\"\"\n", " S.title() -> string\n", " \n", " Return a titlecased version of S, i.e. words start with uppercase\n", " characters, all remaining cased characters have lowercase.\n", " \"\"\"\n", " return \"\"\n", "\n", " def translate(self, table, deletechars=None): \n", " \"\"\"\n", " 转换,需要先做一个对应表,最后一个表示删除字符集合\n", " intab = \"aeiou\"\n", " outtab = \"12345\"\n", " trantab = maketrans(intab, outtab)\n", " str = \"this is string example....wow!!!\"\n", " print str.translate(trantab, 'xm')\n", " \"\"\"\n", "\n", " \"\"\"\n", " S.translate(table [,deletechars]) -> string\n", " \n", " Return a copy of the string S, where all characters occurring\n", " in the optional argument deletechars are removed, and the\n", " remaining characters have been mapped through the given\n", " translation table, which must be a string of length 256 or None.\n", " If the table argument is None, no translation is applied and\n", " the operation simply removes the characters in deletechars.\n", " \"\"\"\n", " return \"\"\n", "\n", " def upper(self): \n", " \"\"\"\n", " S.upper() -> string\n", " \n", " Return a copy of the string S converted to uppercase.\n", " \"\"\"\n", " return \"\"\n", "\n", " def zfill(self, width): \n", " \"\"\"方法返回指定长度的字符串,原字符串右对齐,前面填充0。\"\"\"\n", " \"\"\"\n", " S.zfill(width) -> string\n", " \n", " Pad a numeric string S with zeros on the left, to fill a field\n", " of the specified width. The string S is never truncated.\n", " \"\"\"\n", " return \"\"\n", "\n", " def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown\n", " pass\n", "\n", " def _formatter_parser(self, *args, **kwargs): # real signature unknown\n", " pass\n", "\n", " def __add__(self, y): \n", " \"\"\" x.__add__(y) <==> x+y \"\"\"\n", " pass\n", "\n", " def __contains__(self, y): \n", " \"\"\" x.__contains__(y) <==> y in x \"\"\"\n", " pass\n", "\n", " def __eq__(self, y): \n", " \"\"\" x.__eq__(y) <==> x==y \"\"\"\n", " pass\n", "\n", " def __format__(self, format_spec): \n", " \"\"\"\n", " S.__format__(format_spec) -> string\n", " \n", " Return a formatted version of S as described by format_spec.\n", " \"\"\"\n", " return \"\"\n", "\n", " def __getattribute__(self, name): \n", " \"\"\" x.__getattribute__('name') <==> x.name \"\"\"\n", " pass\n", "\n", " def __getitem__(self, y): \n", " \"\"\" x.__getitem__(y) <==> x[y] \"\"\"\n", " pass\n", "\n", " def __getnewargs__(self, *args, **kwargs): # real signature unknown\n", " pass\n", "\n", " def __getslice__(self, i, j): \n", " \"\"\"\n", " x.__getslice__(i, j) <==> x[i:j]\n", " \n", " Use of negative indices is not supported.\n", " \"\"\"\n", " pass\n", "\n", " def __ge__(self, y): \n", " \"\"\" x.__ge__(y) <==> x>=y \"\"\"\n", " pass\n", "\n", " def __gt__(self, y): \n", " \"\"\" x.__gt__(y) <==> x>y \"\"\"\n", " pass\n", "\n", " def __hash__(self): \n", " \"\"\" x.__hash__() <==> hash(x) \"\"\"\n", " pass\n", "\n", " def __init__(self, string=''): # known special case of str.__init__\n", " \"\"\"\n", " str(object='') -> string\n", " \n", " Return a nice string representation of the object.\n", " If the argument is a string, the return value is the same object.\n", " # (copied from class doc)\n", " \"\"\"\n", " pass\n", "\n", " def __len__(self): \n", " \"\"\" x.__len__() <==> len(x) \"\"\"\n", " pass\n", "\n", " def __le__(self, y): \n", " \"\"\" x.__le__(y) <==> x<=y \"\"\"\n", " pass\n", "\n", " def __lt__(self, y): \n", " \"\"\" x.__lt__(y) <==> x x%y \"\"\"\n", " pass\n", "\n", " def __mul__(self, n): \n", " \"\"\" x.__mul__(n) <==> x*n \"\"\"\n", " pass\n", "\n", " @staticmethod # known case of __new__\n", " def __new__(S, *more): \n", " \"\"\" T.__new__(S, ...) -> a new object with type S, a subtype of T \"\"\"\n", " pass\n", "\n", " def __ne__(self, y): \n", " \"\"\" x.__ne__(y) <==> x!=y \"\"\"\n", " pass\n", "\n", " def __repr__(self): \n", " \"\"\" x.__repr__() <==> repr(x) \"\"\"\n", " pass\n", "\n", " def __rmod__(self, y): \n", " \"\"\" x.__rmod__(y) <==> y%x \"\"\"\n", " pass\n", "\n", " def __rmul__(self, n): \n", " \"\"\" x.__rmul__(n) <==> n*x \"\"\"\n", " pass\n", "\n", " def __sizeof__(self): \n", " \"\"\" S.__sizeof__() -> size of S in memory, in bytes \"\"\"\n", " pass\n", "\n", " def __str__(self): \n", " \"\"\" x.__str__() <==> str(x) \"\"\"\n", " pass\n", "\n", "str" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Kevin Liang\n" ] } ], "source": [ "# 字符串拼接\n", "LastName = 'Liang'\n", "FirstName = 'Kevin'\n", "\n", "MyName = FirstName + ' ' + LastName\n", "print(MyName)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "liangliangliang\n" ] } ], "source": [ "# 字符串重复\n", "print('liang' * 3)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串长度\n", "len('liang')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**字符串索引,分片的使用:**\n", "\n", "之前提到过,字符串是字符的一个有序集合,我们可以操作这个集合。\n", "\n", "通过 **str[index]** 来获取这个字符串中具体某个位置的字符:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'l'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'i'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'a'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'n'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'g'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str1 = 'liang'\n", "str1[0]\n", "str1[1]\n", "str1[2]\n", "str1[3]\n", "str1[4]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "上面例子中 **[ ]** 中括号里面的数字被称为 **索引** ,字符串中第一个字符的 **索引** 是 **0**, 然后依次递增。" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "字符串也可以取出一定范围内的字符,叫 **分片** 。\n", "\n", "通过 **str[star_index: end_index]** 来获取起始索引 ~ 结束索引范围中的字符,但是注意不包含结束索引位的字符。\n", "\n", "例如,你要取 0,1,2, 你要取这三个索引位置的字符,从起始索引0 到 索引2 的都取出来,但是取的时候不包含结束索引的字符,所以需要注意你想要取的结束索引的位置 **+1** ,取开始的索引位到这个位置之前的所有字符。" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'lia'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str1[0:3]" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "xiang\n" ] } ], "source": [ "# 取中间到最后\n", "str2 = 'liangxiang'\n", "length = len(str2)\n", "mid = length // 2\n", "print(str2[mid:])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "我缺省了结束索引就会默认取从起始索引到最后一个索引所有的字符。\n", "\n", "也可以缺省起始索引:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "liang\n" ] } ], "source": [ "# 取从开头到中间\n", "print(str2[:mid])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "起始索引和结束索引使用负数,即反转分片,从序列的最后往前取值。" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'iangxia'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str2[-9:-2]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**str[起始索引:结束索引:步长]**\n", "\n", "这里新增了 **步长** 这个概念,在默认情况下,步长为1,即从左至右一个一个取。设置步长可以实现每多少个取一个。看下面的例子,设置步长为2,即每2个取一个,另外一个则跳过不取。" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "liangxiang\n", "lagin\n" ] } ], "source": [ "# 隔一个字符选取\n", "print(str2)\n", "print(str2[::2])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "步长还可以设置为负数,设置为负数则会反转整个序列:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'gnaixgnail'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str2[::-1]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "'ang'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'gna'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'gnail'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str2[2:5]\n", "str2[4:1:-1]\n", "str2[4::-1]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "因为设置了负数步长,整个序列进行了反转。索引取值也要从反过来从大到小取值,例如反转后取分片[4:1]的值,相对应的是正序[2:5]值。 因为反序后的序列取值会包含起始索引和结束索引,\n", "\n", "需要注意的是,反转序列很常用,但是反转序列分片不太符合人类常用数学习惯,不建议使用,原因是难以理解,阅读不友好,使用正序分片后再做反转会好很多。" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**字符串常用方法:**" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'liangxiansen'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'liangxiansen '" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "' liangxiansen'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串strip方法去除字符串两端的空格\n", "\" liangxiansen \".strip()\n", "\" liangxiansen \".lstrip() # 去掉字符串左边的空格\n", "\" liangxiansen \".rstrip() # 去掉字符串右边的空格" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "['Kevin', 'liang']" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "['liang', 'xian', 'sen']" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串split方法分隔字符串返回list\n", "\" Kevin liang \".split() # 默认参数为空格,以空格分割字符串。\n", "\"liang#xian#sen\".split('#') # 也可以传一个字符,通过这个字符分割字符串" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Kevin/Liang\n" ] } ], "source": [ "# 字符串join方法来对字符串进行拼接\n", "name_list = \" Kevin Liang \".split() # 分隔字符串\n", "new_name = \"/\".join(name_list) # 拼接字符串\n", "print(new_name)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串find方法得到字符在字符串中得索引\n", "name = \"Kevin Liang\"\n", "name.find('v')" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'Kevin Ling'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串replace方法字符串替换\n", "name.replace('iang', 'ing') # 需要注意的是,replace 并不是在原字符串上修改,而是基于原字符串返回一个修改后的新字符串" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "'=========Kevin Liang=========='" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串center方法来对字符串居中\n", "name.center(30, '=') # 第一个参数设置字符串宽度,第二个参数设置填充空白的字符串,不传默认为空格" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "是否‘K‘开头:\t True\n", "是否‘g’结尾:\t True\n", "没有特殊字符:\t False\n", "是否全是字母:\t False\n", "是否全是数字:\t False\n", "是否全空白字符:\t False\n", "是否全是小写:\t False\n", "是否全是大写:\t False\n", "是否首字母大写:\t True\n" ] } ], "source": [ "print(\"是否‘K‘开头:\\t\", name.startswith('K')) # 判断什么字符开头\n", "print(\"是否‘g’结尾:\\t\", name.endswith('g')) # 判断什么字符结尾\n", "print(\"没有特殊字符:\\t\", name.isalnum()) # 是否全是字母和数字,并至少有一个字符\n", "print(\"是否全是字母:\\t\", name.isalpha()) # 是否全是字母,并至少有一个字符\n", "print(\"是否全是数字:\\t\", name.isdigit()) # 是否全是数字,并至少有一个字符\n", "print(\"是否全空白字符:\\t\", name.isspace()) # 是否全是空白字符,并至少有一个字符\n", "print(\"是否全是小写:\\t\", name.islower()) # 中的字母是否全是小写\n", "print(\"是否全是大写:\\t\", name.isupper()) # 中的字母是否便是大写\n", "print(\"是否首字母大写:\\t\", name.istitle()) # 是否是首字母大写的" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Kevin Liang\n" ] }, { "data": { "text/plain": [ "'kEVIN lIANG'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'Kevin Liang'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'Kevin liang'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'KEVIN LIANG'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "'kevin liang'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(name)\n", "name.swapcase() # 大小写互换\n", "name.title() # 单词首字母大写\n", "name.capitalize() # 字符串首字母大写,其余字符小写\n", "name.upper() # 全部字符转变为大写\n", "name.lower() # 全部字符转变为小写" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## 元组\n", "\n", "元组是一个不可更改得有序得序列,支持任意类型得,任意嵌套数据\n", "\n", "元组得输写格式:用小括号包裹元素:(1,2,3,\"liang\")" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 创建元组\n", "t = (1, 2, 3, 'liang')\n", "type(t)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "接下来说一个大家都知道的一个关于元组使用的问题:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t1 = (1)\n", "type(t1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "从之前我们知道元组的定义就是两个括号包裹住,就是元组,但是上面的例子查看类型却不是元组。\n", "\n", "只有一个元素,这样的写法Python解释器不认为这是一个元组,如果只有一个元素,正确的写写法应该是:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t2 = (1,)\n", "type(t2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "需要在元素后面加一个逗号 “,” 让解释器知道你这是一个元组,当然还有调用 Python 的 **tuple** 函数来创建元组对象。" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "tuple" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "()" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "('l', 'i', 'a', 'n', 'g')" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t3 = tuple()\n", "t4 = tuple('liang')\n", "type(t3)\n", "type(t4)\n", "\n", "t3\n", "t4" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "通过tuple 可以创建空元组,也可以将另一个序列变成元组。" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "元组的分片和前面说的大字符串分片一摸一样:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "(4, 5, 6)\n", "(4, 5, 6, 7, 8, 9, (1, 2, 3))\n", "(1, 2, 3, 4, 5, 6)\n", "(1, 2, 3)\n", "(7, 8)\n", "(1, 2, 3, 4, 5, 6, 7, 8, 9, (1, 2, 3))\n", "(1, 3, 5, 7, 9)\n", "1\n" ] } ], "source": [ "# 元组嵌套\n", "tp = (1, 2, 3, 4, 5, 6, 7, 8, 9, (1, 2, 3),)\n", "print(tp[0]) # []中输入索引进行分片,索引起始位为0\n", "print(tp[3:6]) # 显示4~6得元素\n", "print(tp[3:]) # 显示4到最后\n", "print(tp[:6]) # 显示从开头到7的元素\n", "print(tp[-1]) # 显示倒数第一个\n", "print(tp[-4:-2]) # 显示倒数第4个到倒数第二个,(范围切片,结束位不包括在内,即\"到什么什么之前\")\n", "print(tp[:]) # 显示全部\n", "print(tp[::2]) # 按照步长为2,显示全部,步长即两个元素之间索引闲差多少执行一次\n", "print(tp[9][0]) # 嵌套分片" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# index方法查找元素相对应得索引\n", "tp.index(9)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# count查看元素在元组中得数量\n", "tp.count(3) " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "你可能疑惑,加上后面嵌套的元组里面也有一个3,应该是2个3啊; 是的,是找不出来的。 序列里面嵌套序列,对外围序列来说,里面嵌套的序列对他来说是一个对象,它是不管这个对象里面有什么的。" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## 列表\n", "\n", "**List** 是Python 中最灵活的有序的集合,列表可以包含任何类型的对象:数字、字符串、甚至其他列表。支持在原处修改(可修改的),也可以进行分片操作\n", "\n", "List书写格式用 **[ ]** 包裹起来,元素与元素之间用 \",\" 逗号分隔:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = []\n", "type(l)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "list 函数还可以将其他序列转换成列表:" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "['l', 'i', 'a', 'n', 'g']" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list('liang')\n", "list((1, 2, 3, 4, ))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**列表分片:**\n", "\n", "其他序列的分片操作是在原有数据上筛选出想要的数据,并不会修改原数据内容;\n", "\n", "但是由于list是一个灵活可修改的有序序列,list是可以修改原数据的。" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "2" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "[4, 5, 6]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "[4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "10" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "[2, 3, 4, 5, 6]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "[[10, 11, 22, 33, 44], 9, 8, 7, 6, 5, 4, 3, 2, 1]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "[1, 3, 5, 7, 9]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 创建了换一个List, 而且里面还嵌套了List\n", "list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]\n", "\n", "list1[0]\n", "list1[1]\n", "list1[3:6]\n", "list1[3:]\n", "list1[:6]\n", "list1[-1][0]\n", "list1[-9:-4]\n", "list1[::-1]\n", "list1[::2]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "通过分片取出对应索引为止的 Value, 然后通过对这个索引位置重新赋值,就会修改原list中该索引位置的值:" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[111, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]\n" ] } ], "source": [ "list1[0] = 111\n", "print(list1)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Kevin', 'Lina', 'Eric', 'Alex', 'Lina', 'Liangxiansen']\n" ] } ], "source": [ "# 列表append方法对列表中添加元素\n", "\n", "list2 = ['Kevin', 'Lina', 'Eric', 'Alex', 'Lina']\n", "list2.append('Liangxiansen')\n", "print(list2)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 列表count方法查看指定元素在列表中的数量\n", "list2.count('Lina')" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Kevin', 'Lina', 'Eric', 'Alex', 'Lina', 'Liangxiansen']\n" ] }, { "data": { "text/plain": [ "'Liangxiansen'" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "['Kevin', 'Lina', 'Eric', 'Alex', 'Lina']\n" ] } ], "source": [ "# 列表pop方法删除列表中的最后一个元素\n", "print(list2)\n", "list2.pop()\n", "print(list2)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Kevin', 'Lina', 'Eric', 'Alex', 'Lina']\n", "['Kevin', 'Eric', 'Alex', 'Lina']\n" ] } ], "source": [ "# 列表remove方法删除列表指定元素,执行一次只会删除一个,默认是删除找到的第一个。\n", "print(list2)\n", "list2.remove('Lina')\n", "print(list2)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 列表index方法获取指定的元素的索引\n", "list2.index('Alex')" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Kevin', 'Eric', 'Alex', 'Lina', 111, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]\n" ] } ], "source": [ "# 列表extend方法拼接列表\n", "list2.extend(list1)\n", "print(list2)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "TypeError", "evalue": "unorderable types: int() < str()", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mlist2\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msort\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlist2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: unorderable types: int() < str()" ] } ], "source": [ "list2.sort()\n", "print(list2)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "TypeError", "evalue": "unorderable types: list() < int()", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mlist1\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msort\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unorderable types: list() < int()" ] } ], "source": [ "list1.sort()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "上面两个报错是在使用列表sort()方法的时候,里面的元素要统一类型,不要有对象。" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "list3 = [7, 3, 2, 6, 9, 0, 5, 1, 4, 8]\n", "list3.sort()\n", "print(list3)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "[8, 4, 1, 5, 0, 9, 6, 2, 3, 7]" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "[8, 4, 1, 5, 0, 9, 6, 2, 3, 7]\n" ] } ], "source": [ "# 列表reverse方法对列表进行反转\n", "list3 = [7, 3, 2, 6, 9, 0, 5, 1, 4, 8]\n", "list3[::-1]\n", "list3.reverse()\n", "print(list3)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "List 的reverse方法只会根据索引粗暴的反转 List, 并不会做排序,和分片 **[::-1]** 效果一样" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[8, 4, 1, 5, 0, 9, 6, 2, 3, 7]\n", "[8, 4, '66', 1, 5, 0, 9, 6, 2, 3, 7]\n" ] } ], "source": [ "# 列表insert方法在列表的指定位置插入新值。\n", "print(list3)\n", "list3.insert(2, '66') # 接收两个参数,第一个是索引,第二个是值,\n", "print(list3)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[]\n" ] } ], "source": [ "# 列表clear方法清空列表\n", "list3.clear()\n", "print(list3)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "下面我写了一个处理多层嵌套List 的一个例子,看下结果就行了,这里不用学习。" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 5, [9999, 4, 3, 5, [9999, 8, [88, 9999, 2], 3, 5], 2, 6], 9999, [3, 6, 9999, [9999, 2], 3], 8]\n" ] } ], "source": [ "# 使用递归遍历多层嵌套List,把所有的9替换成9999\n", "that_list = [1, 5, [9, 4, 3, 5, [9, 8, [88, 9, 2], 3, 5], 2, 6], 9, [3, 6, 9, [9, 2], 3], 8] # 创建多层嵌套list\n", "\n", "# 创建递归函数\n", "def change_all(ll):\n", " for i in ll:\n", " if i == 9:\n", " key = ll.index(i)\n", " ll[key] = 9999\n", " elif isinstance(i, list): # 如果该对象是list的实例\n", " change_all(i) # 再次调用自己\n", "\n", "\n", "change_all(that_list)\n", "print(that_list)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## 字典\n", "\n", "列表允许你通过一个变量存储大量的信息,但试想以下场景,用列表实现就可能 效率较低了:\n", "\n", "  1. 存储的信息量越来越多,有的时候找一个数据可能要循环整个列表,耗时较长。\n", "\n", "  2. 单个元素包含的信息量变多时,比如,之前只是存储姓名列表,现在是要存 储姓名、年龄、身份证号、地址、工作等这个人的很多信息,用列表去存储 很费劲\n", "\n", "  3. 要求存储的数据是不重复,我们知道列表是允许的重复值的,当然想存储时 就让我的数据默认就是唯一的话,用列表就不可以了\n", " \n", "\n", "以上这些是列表不擅长的地方,却恰恰是接下来要讲的 **dict** 所擅长的方面, dict 使用 key-value 的形式存储数据, dict 的 key 是唯一的,所以你可以通过 key 来唯一的定位到你的数据。之所以叫字典(在其它语言中称为 map),是因为 dict 的数据结构跟我们生活中用的字典是一样的,查英文字典时,输入单词,就可以 定位到这个单词意思的详细解释,其中这个单词就是 key,对应的词义解释就是 value." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "字典有如下特点: \n", "\n", " 1. key-value 格式,key 是唯一的\n", "\n", " 2. 无序,与列表有序的特点不同,字典是无序的,列表之所以有序是因为你需要通过索引来定位相应元素,而字典已经可以通过 key 来定位相应 value,因 此为了避免浪费存储空间,字典不会对数据的位置进行纪录,当然如果你想 让其变成有序的,也是有方法的,这个我们以后再讲。\n", "\n", " 4. 查询速度很快, dict是基于hash表的原理实现的, 是根据关键字(Key/value) 而直接访问在内存存储位置的数据结构。也就是说,它通过把键值通过一个 函数的计算,映射到表中一个位置来访问记录,这加快了查找速度。这个映 射函数称做散列函数,存放记录的数组称做散列表。由于通过一个 key 的索 引表就直接定位到了内存地址,所以查询一个只有 100 条数据的字典和一个 100 万条数据的字典的速度是查不多的。" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'age': 12, 'job': 'IT', 'name': 'Kevin'}\n", "Kevin\n", "12\n", "IT\n" ] } ], "source": [ "# 创建字典, Key/Value 格式\n", "\n", "user_profiles = {\n", " \"name\": \"Kevin\",\n", " \"age\": 12,\n", " \"job\": \"IT\"\n", "}\n", "print(user_profiles)\n", "print(user_profiles['name'])\n", "print(user_profiles['age'])\n", "print(user_profiles['job'])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" }, "solution2": "hidden", "solution2_first": true }, "source": [ "**字典(dict)** 由一对花括号 **{ }** 包含,里面的每一组 Key:value 数据,以逗号分隔, Key 必须是字符串。\n", "\n", "每一个 **Dict** 对象都包含以下方法:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "solution2": "hidden" }, "outputs": [], "source": [ "class dict(object):\n", " \"\"\"\n", " dict() -> new empty dictionary\n", " dict(mapping) -> new dictionary initialized from a mapping object's\n", " (key, value) pairs\n", " dict(iterable) -> new dictionary initialized as if via:\n", " d = {}\n", " for k, v in iterable:\n", " d[k] = v\n", " dict(**kwargs) -> new dictionary initialized with the name=value pairs\n", " in the keyword argument list. For example: dict(one=1, two=2)\n", " \"\"\"\n", "\n", " def clear(self): # real signature unknown; restored from __doc__\n", " \"\"\" 清除内容 \"\"\"\n", " \"\"\" D.clear() -> None. Remove all items from D. \"\"\"\n", " pass\n", "\n", " def copy(self): # real signature unknown; restored from __doc__\n", " \"\"\" 浅拷贝 \"\"\"\n", " \"\"\" D.copy() -> a shallow copy of D \"\"\"\n", " pass\n", "\n", " @staticmethod # known case\n", " def fromkeys(S, v=None): # real signature unknown; restored from __doc__\n", " \"\"\"\n", " dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n", " v defaults to None.\n", " \"\"\"\n", " pass\n", "\n", " def get(self, k, d=None): # real signature unknown; restored from __doc__\n", " \"\"\" 根据key获取值,d是默认值 \"\"\"\n", " \"\"\" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. \"\"\"\n", " pass\n", "\n", " def has_key(self, k): # real signature unknown; restored from __doc__\n", " \"\"\" 是否有key \"\"\"\n", " \"\"\" D.has_key(k) -> True if D has a key k, else False \"\"\"\n", " return False\n", "\n", " def items(self): # real signature unknown; restored from __doc__\n", " \"\"\" 所有项的列表形式 \"\"\"\n", " \"\"\" D.items() -> list of D's (key, value) pairs, as 2-tuples \"\"\"\n", " return []\n", "\n", " def iteritems(self): # real signature unknown; restored from __doc__\n", " \"\"\" 项可迭代 \"\"\"\n", " \"\"\" D.iteritems() -> an iterator over the (key, value) items of D \"\"\"\n", " pass\n", "\n", " def iterkeys(self): # real signature unknown; restored from __doc__\n", " \"\"\" key可迭代 \"\"\"\n", " \"\"\" D.iterkeys() -> an iterator over the keys of D \"\"\"\n", " pass\n", "\n", " def itervalues(self): # real signature unknown; restored from __doc__\n", " \"\"\" value可迭代 \"\"\"\n", " \"\"\" D.itervalues() -> an iterator over the values of D \"\"\"\n", " pass\n", "\n", " def keys(self): # real signature unknown; restored from __doc__\n", " \"\"\" 所有的key列表 \"\"\"\n", " \"\"\" D.keys() -> list of D's keys \"\"\"\n", " return []\n", "\n", " def pop(self, k, d=None): # real signature unknown; restored from __doc__\n", " \"\"\" 获取并在字典中移除 \"\"\"\n", " \"\"\"\n", " D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n", " If key is not found, d is returned if given, otherwise KeyError is raised\n", " \"\"\"\n", " pass\n", "\n", " def popitem(self): # real signature unknown; restored from __doc__\n", " \"\"\" 获取并在字典中移除 \"\"\"\n", " \"\"\"\n", " D.popitem() -> (k, v), remove and return some (key, value) pair as a\n", " 2-tuple; but raise KeyError if D is empty.\n", " \"\"\"\n", " pass\n", "\n", " def setdefault(self, k, d=None): # real signature unknown; restored from __doc__\n", " \"\"\" 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 \"\"\"\n", " \"\"\" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D \"\"\"\n", " pass\n", "\n", " def update(self, E=None, **F): # known special case of dict.update\n", " \"\"\" 更新\n", " {'name':'alex', 'age': 18000}\n", " [('name','sbsbsb'),]\n", " \"\"\"\n", " \"\"\"\n", " D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n", " If E present and has a .keys() method, does: for k in E: D[k] = E[k]\n", " If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v\n", " In either case, this is followed by: for k in F: D[k] = F[k]\n", " \"\"\"\n", " pass\n", "\n", " def values(self): # real signature unknown; restored from __doc__\n", " \"\"\" 所有的值 \"\"\"\n", " \"\"\" D.values() -> list of D's values \"\"\"\n", " return []\n", "\n", " def viewitems(self): # real signature unknown; restored from __doc__\n", " \"\"\" 所有项,只是将内容保存至view对象中 \"\"\"\n", " \"\"\" D.viewitems() -> a set-like object providing a view on D's items \"\"\"\n", " pass\n", "\n", " def viewkeys(self): # real signature unknown; restored from __doc__\n", " \"\"\" D.viewkeys() -> a set-like object providing a view on D's keys \"\"\"\n", " pass\n", "\n", " def viewvalues(self): # real signature unknown; restored from __doc__\n", " \"\"\" D.viewvalues() -> an object providing a view on D's values \"\"\"\n", " pass\n", "\n", " def __cmp__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__cmp__(y) <==> cmp(x,y) \"\"\"\n", " pass\n", "\n", " def __contains__(self, k): # real signature unknown; restored from __doc__\n", " \"\"\" D.__contains__(k) -> True if D has a key k, else False \"\"\"\n", " return False\n", "\n", " def __delitem__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__delitem__(y) <==> del x[y] \"\"\"\n", " pass\n", "\n", " def __eq__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__eq__(y) <==> x==y \"\"\"\n", " pass\n", "\n", " def __getattribute__(self, name): # real signature unknown; restored from __doc__\n", " \"\"\" x.__getattribute__('name') <==> x.name \"\"\"\n", " pass\n", "\n", " def __getitem__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__getitem__(y) <==> x[y] \"\"\"\n", " pass\n", "\n", " def __ge__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__ge__(y) <==> x>=y \"\"\"\n", " pass\n", "\n", " def __gt__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__gt__(y) <==> x>y \"\"\"\n", " pass\n", "\n", " def __init__(self, seq=None, **kwargs): # known special case of dict.__init__\n", " \"\"\"\n", " dict() -> new empty dictionary\n", " dict(mapping) -> new dictionary initialized from a mapping object's\n", " (key, value) pairs\n", " dict(iterable) -> new dictionary initialized as if via:\n", " d = {}\n", " for k, v in iterable:\n", " d[k] = v\n", " dict(**kwargs) -> new dictionary initialized with the name=value pairs\n", " in the keyword argument list. For example: dict(one=1, two=2)\n", " # (copied from class doc)\n", " \"\"\"\n", " pass\n", "\n", " def __iter__(self): # real signature unknown; restored from __doc__\n", " \"\"\" x.__iter__() <==> iter(x) \"\"\"\n", " pass\n", "\n", " def __len__(self): # real signature unknown; restored from __doc__\n", " \"\"\" x.__len__() <==> len(x) \"\"\"\n", " pass\n", "\n", " def __le__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__le__(y) <==> x<=y \"\"\"\n", " pass\n", "\n", " def __lt__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__lt__(y) <==> x a new object with type S, a subtype of T \"\"\"\n", " pass\n", "\n", " def __ne__(self, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__ne__(y) <==> x!=y \"\"\"\n", " pass\n", "\n", " def __repr__(self): # real signature unknown; restored from __doc__\n", " \"\"\" x.__repr__() <==> repr(x) \"\"\"\n", " pass\n", "\n", " def __setitem__(self, i, y): # real signature unknown; restored from __doc__\n", " \"\"\" x.__setitem__(i, y) <==> x[i]=y \"\"\"\n", " pass\n", "\n", " def __sizeof__(self): # real signature unknown; restored from __doc__\n", " \"\"\" D.__sizeof__() -> size of D in memory, in bytes \"\"\"\n", " pass\n", "\n", " __hash__ = None\n", "\n", "dict" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'age': 12, 'job': 'IT', 'name': 'Liangxiansen'}\n" ] } ], "source": [ "# 使用key,修改value\n", "user_profiles['name'] = 'Liangxiansen' # 修改name对应的value,如果name不存在就会创建一个这样得对应值\n", "print(user_profiles)" ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'Liangxiansen'" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "{'age': 12, 'job': 'IT'}\n" ] } ], "source": [ "# 字典的pop方法删除指定一条数据\n", "user_profiles.pop('name') # 删除'name'这条数据\n", "print(user_profiles)" ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "('age', 12)" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "{'job': 'IT'}\n" ] } ], "source": [ "# 字典的popitem方法会随机删除一条字典得数据(尽量不要使用)\n", "user_profiles.popitem() # 随机删除一条数据,dict为空得时候会报错\n", "print(user_profiles)" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('age', 12), ('job', 'IT'), ('name', 'lianglian')]\n" ] } ], "source": [ "# 字典的items方法可以将字典的key,value以字典视图的形式返回(尽量不要使用,大字典的时候,你没发确认有多大数据)\n", "user_info = {\n", " \"name\": \"lianglian\",\n", " \"age\": 12,\n", " \"job\": \"IT\"\n", "}\n", "\n", "new_user_info = list(user_info.items()) # 将dict的key,value转换成列表字典视图形式的list,再通过list函数转换成真正可操作的list\n", "print(new_user_info)" ] }, { "cell_type": "code", "execution_count": 117, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['lianglian', 'IT', 12]\n" ] } ], "source": [ "# 字典的values方法可以将字典的value以字典视图形式返回(大字典得时候,谨慎使用,你没法确认下面嵌套字典有多大数据)\n", "new_user_info = list(user_info.values()) # 将dict的key,value转换成字典视图形式的list,再通过list函数转换成真正可操作的list\n", "print(new_user_info)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dict_keys(['age', 'job', 'name'])\n", "['age', 'job', 'name']\n" ] } ], "source": [ "# 字典的keys方法可以将字典的key以字典视图的形式返回(相对上面两种推荐使用这种,通过key去取value)\n", "print(user_info.keys()) # 将dict的key转换成字典视图形式的list,再通过list函数转换成真正可操作的list\n", "print(list(user_info.keys())) # 使用list函数变成列表。" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n", "lianglian\n" ] } ], "source": [ "# 字典的get方法安全的去查询一个key得value,不存在得key不会报错\n", "\n", "print(user_info.get('na')) # 查找一个key,如果存在则返回value,如果不存在不会报错,返回None\n", "print(user_info.get('name'))" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "lianglian\n", "{'age': 12, 'job': 'IT', 'name': 'lianglian'}\n" ] } ], "source": [ "# 字典的setdefault方法可以安全得去修改一个key得值,这个key存在不会覆盖掉\n", "\n", "print(user_info.setdefault('name','Test'))\n", "print(user_info)\n", "# 找一个key为'name'的记录,如果这个key不存在,那就创建一个叫'name'的key,\n", "# 并且将其value设置为'Test',如果这个key存在,就直接返回这个key的value" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'age': 18, 'job': 'IT', 'address': 'BeiJing', 'name': 'liang'}\n" ] } ], "source": [ "# 通过字典的update方法拿一个新的字典去更新一个旧的字典\n", "\n", "test_dict = {\n", " 'age': 18,\n", " 'name': 'liang',\n", " 'address': 'BeiJing'\n", "}\n", "\n", "user_info.update(test_dict) \n", "print(user_info)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{}\n" ] } ], "source": [ "# 字典的clear方法清除字典全部内容,保留字典类型\n", "\n", "test_dict.clear() # 清空dict\n", "print(test_dict)" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'age': 12, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}, 'name': 'lianglian'}\n", "{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}}\n", "{'age': 16, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}, 'name': 'lianglian'}\n", "{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}}\n" ] } ], "source": [ "# 字典的copy方法copy属于浅copy\n", "profiles_info = {\n", " \"name\": \"lianglian\",\n", " \"age\": 12,\n", " \"job\": \"IT\",\n", " \"hobby\": {\n", " \"book\": \"三国演义\",\n", " \"movement\": \"skateboard\" \n", " }\n", "}\n", "\n", "new_profiles_info = profiles_info.copy()\n", "print(profiles_info)\n", "print(new_profiles_info)\n", "\n", "profiles_info['age'] = 16\n", "profiles_info['hobby']['book'] = '三体'\n", "print(profiles_info)\n", "print(new_profiles_info)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "按理说我copy了一份profiles_info 到 new_profiles_info 它们应该是独立得两份数据,那么我修改profiles_info, new_profiles_info是不会改变的,这里在修改'age'得时候确实是这样,没有错,但是修改profiles_info嵌套得字典里面得内容得时候new_profiles_info里面的内容也变了,为什么呢? 看下面图:" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "![lightcopy](lightcopy.png)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "![deepcopy](deepcopy.png)" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'age': 12, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}, 'name': 'lianglian'}\n", "{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}}\n", "{'age': 16, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}, 'name': 'lianglian'}\n", "{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}}\n" ] } ], "source": [ "# 字典的copy模块的deepcopy方法实现深copy\n", "import copy\n", "profiles_info = {\n", " \"name\": \"lianglian\",\n", " \"age\": 12,\n", " \"job\": \"IT\",\n", " \"hobby\": {\n", " \"book\": \"三国演义\",\n", " \"movement\": \"skateboard\" \n", " }\n", "}\n", "\n", "new_profiles_info = copy.deepcopy(profiles_info)\n", "print(profiles_info)\n", "print(new_profiles_info)\n", "\n", "profiles_info['age'] = 16\n", "profiles_info['hobby']['book'] = '三体'\n", "print(profiles_info)\n", "print(new_profiles_info)" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'age': 16, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}, 'name': 'lianglian'}\n", "age 16\n", "job IT\n", "hobby {'movement': 'skateboard', 'book': '三体'}\n", "name lianglian\n" ] } ], "source": [ "# 遍历字典\n", "\n", "print(profiles_info)\n", "\n", "for key in profiles_info:\n", " value = profiles_info[key]\n", " print(key, value)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## 集合\n", "\n", "python 的 **集合(set)** 和其他语言类似, 是一个无序 **不重复** 元素集, 基本功能包括关系测 适合消除重复元素. 集合对象还支持 **union(联合)**, **intersection(交)**, **difference(差)** 和 **sysmmetric difference(对称差集)**等数学运算. \n", "\n", "set 支持 x in set, len(set),和 for x in set。作为一个无序的集合,set 不记录元素位置或者插入点。因此,set 不支持 indexing, slicing, 或其它类序列 (sequence-like)的操作。 \n", "\n", "与列表和元组不同,集合是无序的,也无法通过数字进行索引。此外,集合中的元素 **不能重复**:" ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'e', 'o', 'l', 'h'}\n", "['h', 'e', 'l', 'l', 'o']\n" ] } ], "source": [ "# 通过set关键字函数来创建集合\n", "s = set('hello')\n", "l = list('hello')\n", "print(s)\n", "print(l)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "如上结果中少了一个\"l\",set是会默认去除重复的。" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "{'d', 'e', 'h', 'l', 'o', 'r', 'w'}" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "{'h', 'e', 'w', 'o', 'd', 'r', 'l'}\n", "{'o', 'l'}\n", "{'o', 'l'}\n", "{'e', 'h'}\n", "{'e', 'h'}\n", "{'e', 'w', 'd', 'r', 'h'}\n", "{'e', 'w', 'd', 'r', 'h'}\n" ] } ], "source": [ "t = set('world')\n", "\n", "s.union(t) # s 和 t 的并集(两个合并到一块)\n", "print(s | t)\n", "\n", "print(s.intersection(t)) # s 和 t的交集(取出两个都有的)\n", "print(s & t)\n", "\n", "print(s.difference(t)) # 求差集(项在s中,但是不在t中)\n", "print(s - t) \n", "\n", "print(s.symmetric_difference(t)) # 对称差集(两个中不相同的)\n", "print(s ^ t) " ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "{'e', 'h', 'l', 'o'}" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "{'e', 'o', 'l', 'u', 'h'}\n" ] } ], "source": [ "# 集合add方法添加新元素\n", "s\n", "s.add('u')\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'world', 'e', 'o', 'H', 'l'}\n", "{'H', 'e', 'w', 'o', 'd', 'r', 'l'}\n" ] } ], "source": [ "# 集合update方法添加多个元素,可以接受迭代的对象,循环add,批量添加\n", "# add <-->update 的区别\n", "\n", "t = set(\"Hello\")\n", "t.add(\"world\") \n", "print(t) \n", "\n", "t1 = set(\"Hello\")\n", "t1.update(\"world\")\n", "print(t1)" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'e', 'o', 'H', 'l'}\n", "{'H', 'e'}\n" ] } ], "source": [ "# 差集更新(在s中有的,在t中没有更新到s)\n", "s = set(\"Hello\")\n", "t = set(\"World\")\n", "\n", "print(s)\n", "s.difference_update(t)\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'e', 'o', 'l'}\n" ] } ], "source": [ "# 集合remove方法,移除指定值,如果没有会报错\n", "s = set(\"Hello\")\n", "s.remove(\"H\")\n", "print(s) " ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'e', 'o', 'H', 'l'}\n" ] } ], "source": [ "# 集合discard方法,移除指定值,如果没有不会报错\n", "s = set(\"Hello\")\n", "s.discard(\"h\")\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "删除:{'#4'}\n", "添加:{'#3'}\n", "更新{'#2', '#1'}\n", "\n" ] } ], "source": [ "old_dict = {\n", " \"#1\": 8,\n", " \"#2\": 4,\n", " \"#4\": 2,\n", "}\n", "\n", "new_dict = {\n", " \"#1\": 4,\n", " \"#2\": 4,\n", " \"#3\": 2,\n", "}\n", "\n", "# old_dict 中没有, new_dict 中有的加到 old_dict\n", "old_set = set(old_dict.keys())\n", "new_set = set(new_dict.keys())\n", "\n", "remove_set = old_set.difference(new_set)\n", "add_set = new_set.difference(old_set)\n", "update_set = old_set.intersection(new_set)\n", "\n", "print(\"删除:%s\\n添加:%s\\n更新%s\\n\" % (remove_set, add_set, update_set))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## 运算\n", "\n", "### 比较运算\n", "![比较运算](比较运算.png)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### 赋值运算\n", "![赋值运算](赋值运算.png)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### 逻辑运算\n", "![逻辑运算](逻辑运算.png)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### 成员运算\n", "![成员运算](成员运算.png)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### 身份运算\n", "![身份运算](身份运算.png)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### 位运算\n", "![位运算](位运算.png)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### 运算优先级\n", "![运算优先级](运算优先级.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 内存指针" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "值传递:我创建了两个变量,分别指向内存中对应的两个地址空间的值:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "liangxiansen\n", "Kevin\n", "name1 内存地址: 4350694512\n", "name2 内存地址: 4322625272\n" ] } ], "source": [ "name1 = 'liangxiansen'\n", "name2 = 'Kevin'\n", "\n", "print(name1)\n", "print(name2)\n", "\n", "print('name1 内存地址:', id(name1))\n", "print('name2 内存地址:', id(name2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![值传递](value1.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "指针传递:我创建了一个变量,使用另一个变量赋值的内存指针赋值:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "liangxiansen\n", "liangxiansen\n", "name1 内存地址: 4350694512\n", "name3 内存地址: 4350694512\n" ] } ], "source": [ "name3 = name1\n", "\n", "print(name1)\n", "print(name3)\n", "\n", "print('name1 内存地址:', id(name1))\n", "print('name3 内存地址:', id(name3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![地址传递](value2.png)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.2" }, "toc": { "colors": { "hover_highlight": "#DAA520", "navigate_num": "#000000", "navigate_text": "#333333", "running_highlight": "#FF0000", "selected_highlight": "#FFD700", "sidebar_border": "#EEEEEE", "wrapper_background": "#FFFFFF" }, "moveMenuLeft": true, "nav_menu": { "height": "48px", "width": "252px" }, "navigate_menu": true, "number_sections": false, "sideBar": true, "threshold": 4, "toc_cell": true, "toc_section_display": "block", "toc_window_display": false, "widenNotebook": false } }, "nbformat": 4, "nbformat_minor": 2 }