Python

Posted yangchangjie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python相关的知识,希望对你有一定的参考价值。

python

基本数据运算符

算术运算符

运算符 描述 实例(a=10,b=20)
+ 加 - 两个对象相加 a + b 输出结果 30
- 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -10
* 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 200
/ 除 - x除以y b / a 输出结果 2
% 取模 - 返回除法的余数 b % a 输出结果 0
** 幂 - 返回x的y次幂 a**b 为10的20次方, 输出结果 100000000000000000000
// 取整除 - 返回商的整数部分(向下取整 >>> 9//2 4
>>> -9//2 -5

位运算符

运算符 描述 实例
& 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 (a & b) 输出结果 12 ,二进制解释: 0000 1100
| 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。 (a | b) 输出结果 61 ,二进制解释: 0011 1101
^ 按位异或运算符:当两对应的二进位相异时,结果为1 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001
~ 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1 (~a ) 输出结果 -61 ,二进制解释: 1100 0011,在一个有符号二进制数的补码形式。
<< 左移动运算符:运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。 a << 2 输出结果 240 ,二进制解释: 1111 0000
>> 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数 a >> 2 输出结果 15 ,二进制解释: 0000 1111

逻辑运算符

运算符 逻辑表达式 描述 实例
and x and y 布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 (a and b) 返回 20。
or x or y 布尔"或" - 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。 (a or b) 返回 10。
not not x 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 not(a and b) 返回 False

赋值运算符

运算符 描述 实例
= 简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c
+= 加法赋值运算符 c += a 等效于 c = c + a
-= 减法赋值运算符 c -= a 等效于 c = c - a
*= 乘法赋值运算符 c *= a 等效于 c = c * a
/= 除法赋值运算符 c /= a 等效于 c = c / a
%= 取模赋值运算符 c %= a 等效于 c = c % a
**= 幂赋值运算符 c **= a 等效于 c = c ** a
//= 取整除赋值运算符 c //= a 等效于 c = c // a

比较运算符

运算符 描述 实例
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 true.
<> 不等于 - 比较两个对象是否不相等 (a <> b) 返回 true。这个运算符类似 != 。
> 大于 - 返回x是否大于y (a > b) 返回 False。
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。 (a < b) 返回 true。
>= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
<= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 true。

成员运算符

运算符 描述 实例
in 如果在指定的序列中找到值返回 True,否则返回 False。 x 在 y 序列中 , 如果 x 在 y 序列中返回 True。
not in 如果在指定的序列中没有找到值返回 True,否则返回 False。 x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。

身份运算符

算符 描述 实例
is is 是判断两个标识符是不是引用自一个对象 x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
is not is not 是判断两个标识符是不是引用自不同对象 x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。

基本数据类型

数字

int(整型)

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
数字:
python的数字运算,包括了(加:+,减:-,乘:*;除: / ;双星号:**)等。

	>>> a = 123
	>>> b = 456
	>>> a * b
	56088
	>>> a / b
	0.26973684210526316
	>>> a%b
	123
	>>> a // b
	0
	>>> a + b
	579
	>>> a ** 2
	15129
	>>> len(str(2**100))
	31
	>>> 123.345 ** 2
	15213.989024999999
	>>> print(123.345 ** 2)
	15213.989024999999
	>>> 12.34 * 2
	24.68
	>>> import math
	>>> math.pi
	3.141592653589793
	>>> math.sqrt(2)
	1.4142135623730951
	>>>
	>>> import random
	>>> random.random()
	0.9013111518954912
	>>> random.random()
	0.037732894432051745
	>>> random.random()
	0.8587096319039393
	>>>

int
    class int(object):
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long

    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    If x is outside the integer range, the function returns a long instead.

    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by \'+\' or \'-\' and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int(\'0b100\', base=0)
    """
    def bit_length(self):
    """ 返回表示该数字的时占用的最少位数 """
    """
    int.bit_length() -> int

    Number of bits necessary to represent self in binary.
    >>> bin(37)
    \'0b100101\'
    >>> (37).bit_length()
    """
    return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
    """ 返回该复数的共轭复数 """
    """ Returns self, the complex conjugate of any int. """
    pass

    def __abs__(self):
    """ 返回绝对值 """
    """ x.__abs__() <==> abs(x) """
    pass

    def __add__(self, y):
    """ x.__add__(y) <==> x+y """
    pass

    def __and__(self, y):
    """ x.__and__(y) <==> x&y """
    pass

    def __cmp__(self, y):
    """ 比较两个数大小 """
    """ x.__cmp__(y) <==> cmp(x,y) """
    pass

    def __coerce__(self, y):
    """ 强制生成一个元组 """
    """ x.__coerce__(y) <==> coerce(x, y) """
    pass

    def __divmod__(self, y):
    """ 相除,得到商和余数组成的元组 """
    """ x.__divmod__(y) <==> divmod(x, y) """
    pass

    def __div__(self, y):
    """ x.__div__(y) <==> x/y """
    pass

    def __float__(self):
    """ 转换为浮点类型 """
    """ x.__float__() <==> float(x) """
    pass

    def __floordiv__(self, y):
    """ x.__floordiv__(y) <==> x//y """
    pass

    def __format__(self, *args, **kwargs): # real signature unknown
    pass

    def __getattribute__(self, name):
    """ x.__getattribute__(\'name\') <==> x.name """
    pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
    """ 内部调用 __new__方法或创建对象时传入参数使用 """
    pass

    def __hash__(self):
    """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
    """ x.__hash__() <==> hash(x) """
    pass

    def __hex__(self):
    """ 返回当前数的 十六进制 表示 """
    """ x.__hex__() <==> hex(x) """
    pass

    def __index__(self):
    """ 用于切片,数字无意义 """
    """ x[y:z] <==> x[y.__index__():z.__index__()] """
    pass

    def __init__(self, x, base=10): # known special case of int.__init__
    """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long

    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    If x is outside the integer range, the function returns a long instead.

    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by \'+\' or \'-\' and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int(\'0b100\', base=0)
    # (copied from class doc)
    """
    pass

    def __int__(self):
    """ 转换为整数 """
    """ x.__int__() <==> int(x) """
    pass

    def __invert__(self):
    """ x.__invert__() <==> ~x """
    pass

    def __long__(self):
    """ 转换为长整数 """
    """ x.__long__() <==> long(x) """
    pass

    def __lshift__(self, y):
    """ x.__lshift__(y) <==> x<<y """
    """ 左移 """
    pass

    def __mod__(self, y):
    """ x.__mod__(y) <==> x%y """
    """ 取余"""
    pass

    def __mul__(self, y):
    """ x.__mul__(y) <==> x*y """
    """ 乘"""
    pass

    def __neg__(self):
    """ x.__neg__() <==> -x """
    """ 相反数"""
    pass

    @staticmethod # known case of __new__
    def __new__(S, *more):
    """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
    pass

    def __nonzero__(self):
    """ x.__nonzero__() <==> x != 0 """
    """ 不存在 python3."""
    pass

    def __oct__(self):
    """ 返回改值的 八进制 表示 """
    """ x.__oct__() <==> oct(x) """
    pass

    def __or__(self, y):
    """ x.__or__(y) <==> x|y """
    """ 或"""
    pass

    def __pos__(self):
    """ x.__pos__() <==> +x """
    pass

    def __pow__(self, y, z=None):
    """ 幂,次方 """
    """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
    pass

    def __radd__(self, y):
    """ x.__radd__(y) <==> y+x """
    pass

    def __rand__(self, y):
    """ x.__rand__(y) <==> y&x """
    pass

    def __rdivmod__(self, y):
    """ x.__rdivmod__(y) <==> divmod(y, x) """
    pass

    def __rdiv__(self, y):
    """ x.__rdiv__(y) <==> y/x """
    pass

    def __repr__(self):
    """转化为解释器可读取的形式 """
    """ x.__repr__() <==> repr(x) """
    pass

    def __str__(self):
    """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
    """ x.__str__() <==> str(x) """
    pass

    def __rfloordiv__(self, y):
    """ x.__rfloordiv__(y) <==> y//x """
    pass

    def __rlshift__(self, y):
    """ x.__rlshift__(y) <==> y<<x """
    pass

    def __rmod__(self, y):
    """ x.__rmod__(y) <==> y%x """
    pass

    def __rmul__(self, y):
    """ x.__rmul__(y) <==> y*x """
    pass

    def __ror__(self, y):
    """ x.__ror__(y) <==> y|x """
    pass

    def __rpow__(self, x, z=None):
    """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
    pass

    def __rrshift__(self, y):
    """ x.__rrshift__(y) <==> y>>x """
    pass

    def __rshift__(self, y):
    """ x.__rshift__(y) <==> x>>y """
    pass

    def __rsub__(self, y):
    """ x.__rsub__(y) <==> y-x """
    pass

    def __rtruediv__(self, y):
    """ x.__rtruediv__(y) <==> y/x """
    pass

    def __rxor__(self, y):
    """ x.__rxor__(y) <==> y^x """
    pass

    def __sub__(self, y):
    """ x.__sub__(y) <==> x-y """
    pass

    def __truediv__(self, y):
    """ x.__truediv__(y) <==> x/y """
    pass

    def __trunc__(self, *args, **kwargs):
    """ 返回数值被截取为整形的值,在整形中无意义 """
    pass

    def __xor__(self, y):
    """ x.__xor__(y) <==> x^y """
    pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分母 = 1 """
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 虚数,无意义 """
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分子 = 数字大小 """
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 实属,无意义 """
    """the real part of a complex number"""
</pre>

字符串


a = str("123")
print(a, type(a))# 123 <class \'str\'>

name="Yangchangjie"


>>> var1 = "hello world"
>>> var2 = "yangchangjie"
>>> var1[0]
\'h\'
>>> var2[1:5]
\'angc\'
>>>


列表

切片等操作

names = ["Tom", "Jacks","Ycj"]
a = list()
a.append("name")

>>> s = "spam"
>>> s[0]
\'s\'
>>> s[-1]
\'m\'
>>> s[-2]
\'a\'
>>> s[1]
\'p\'
>>>
>>> s[len(s)-1]
\'m\'
>>> s
\'spam\'
>>> s[1:3]
\'pa\'
>>> s[1:]
\'pam\'
>>> s[:3]
\'spa\'
>>> s[:-1]
\'spa\'
>>> s[:]
\'spam\'
>>>
>>> s + "xyz"
\'spamxyz\'
>>> s
\'spam\'
>>> s * 8
\'spamspamspamspamspamspamspamspam\'
>>> s[0]=\'z\' # 不可变性
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: \'str\' object does not support item assignment
>>> s = \'z\' + s[1:]
>>> s
\'zpam\'
>>>

>>> s
\'zpam\'
>>> s.replace("pa", "xyz")
\'zxyzm\'
>>> s
\'zpam\'
>>>
>>> line = "aaa, bbb, cccc, dd"
>>> line.split(",")
[\'aaa\', \' bbb\', \' cccc\', \' dd\']
>>> s
\'zpam\'
>>> s.upper()
\'ZPAM\'
>>> s.isalpha()
True
>>> line = "aaa, bbb, cccc, dd\\n"
>>> line = line.rstrip()
>>> line
\'aaa, bbb, cccc, dd\'
>>>

基本操作

L = ["a", 123, "spam", 12.345]
a = len(L)  # 4
print(L + [4, 56])  # [\'a\', 123, \'spam\', 12.345, 4, 56]
print(L)  # [\'a\', 123, \'spam\', 12.345] 原来的操作列表没有任何的变化
L.append("A")  # 在列表中在末尾中添加一个字符"A" [\'a\', 123, \'spam\', 12.345, \'A\']
L.pop()   # 在删除列表的尾部元素 [\'a\', 123, \'spam\', 12.345]

M = ["bb", "aa", "cc"]
M.sort()  # [\'aa\', \'bb\', \'cc\'] 升序进行排序 对列表有改变
M.reverse()  # [\'cc\', \'bb\', \'aa\'] 进行翻转

M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]
     ]

print(M[1])  # [4, 5, 6]
print(M[1][1])  # 5

# 列表解析
M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]
     ]


col = [row[0] for row in M]
print(col)  # [1, 4, 7]
col1 = [row[0] + 1 for row in M]
print(col1)  # [2, 5, 8]

col1 = [(row[0]+1) for row in M if (row[0]+1) % 2 == 0]
print(col1)   # [2, 8]偶数 奇数【col1 = [(row[0]+1) for row in M if (row[0]) % 2 == 0]】 5

diag = [M[i][i] for i in [0, 1, 2]]
print(diag)  # [1, 5, 9] 斜对角

doubles = [x * 2 for x in "spam"]
print(doubles)  # [\'ss\', \'pp\', \'aa\', \'mm\']
G = (sum(row) for row in M)  # ()中会创建一个迭代器 用next来访问数据
print(next(G))  # 6
print(next(G))  # 15
print(next(G))  # 24
# 类似的map的操作
list(map(sum, M))  # [6, 15, 24]
\'\'\'
map(func, *iterables) --> map object
    
    Make an iterator that computes the function using arguments from
    each of the iterables.  Stops when the shortest iterable is exhausted.
    创建一个迭代器,该迭代器使用来自的参数计算函数
    每个迭代。当最短的迭代耗尽时停止   
\'\'\'
# 解析语法创建集合和字典

{sum(row) for row in M}  # {24, 6, 15}
dict_ = {i: M[i] for i in range(len(M))}  # {0: [1, 2, 3], 1: [4, 5, 6], 2: [7, 8, 9]}

{ord(row)for row in "SPAM"}  # {80, 65, 83, 77}
dict_ = {row: ord(row) for row in "SPAM"}  # {\'S\': 83, \'P\': 80, \'A\': 65, \'M\': 77}

list
                class list(object):
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable\'s items
        """
        def append(self, p_object): # real signature unknown; restored from __doc__
            """ L.append(object) -- append object to end """
            pass

        def count(self, value): # real signature unknown; restored from __doc__
            """ L.count(value) -> integer -- return number of occurrences of value """
            return 0

        def extend(self, iterable): # real signature unknown; restored from __doc__
            """ L.extend(iterable) -- extend list by appending elements from the iterable """
            pass

        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

        def insert(self, index, p_object): # real signature unknown; restored from __doc__
            """ L.insert(index, object) -- insert object before index """
            pass

        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

        def remove(self, value): # real signature unknown; restored from __doc__
            """
            L.remove(value) -- remove first occurrence of value.
            Raises ValueError if the value is not present.
            """
            pass

        def reverse(self): # real signature unknown; restored from __doc__
            """ L.reverse() -- reverse *IN PLACE* """
            pass

        def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
            """
            L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
            cmp(x, y) -> -1, 0, 1
            """
            pass

        def __add__(self, y): # real signature unknown; restored from __doc__
            """ x.__add__(y) <==> x+y """
            pass

        def __contains__(self, y): # real signature unknown; restored from __doc__
            """ x.__contains__(y) <==> y in x """
            pass

        def __delitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__delitem__(y) <==> del x[y] """
            pass

        def __delslice__(self, i, j): # real signature unknown; restored from __doc__
            """
            x.__delslice__(i, j) <==> del x[i:j]

                       Use of negative indices is not supported.
            """
            pass

        def __eq__(self, y): # real signature unknown; restored from __doc__
            """ x.__eq__(y) <==> x==y """
            pass

        def __getattribute__(self, name): # real signature unknown; restored from __doc__
            """ x.__getattribute__(\'name\') <==> x.name """
            pass

        def __getitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__getitem__(y) <==> x[y] """
            pass

        def __getslice__(self, i, j): # real signature unknown; restored from __doc__
            """
            x.__getslice__(i, j) <==> x[i:j]

                       Use of negative indices is not supported.
            """
            pass

        def __ge__(self, y): # real signature unknown; restored from __doc__
            """ x.__ge__(y) <==> x>=y """
            pass

        def __gt__(self, y): # real signature unknown; restored from __doc__
            """ x.__gt__(y) <==> x>y """
            pass

        def __iadd__(self, y): # real signature unknown; restored from __doc__
            """ x.__iadd__(y) <==> x+=y """
            pass

        def __imul__(self, y): # real signature unknown; restored from __doc__
            """ x.__imul__(y) <==> x*=y """
            pass

        def __init__(self, seq=()): # known special case of list.__init__
            """
            list() -> new empty list
            list(iterable) -> new list initialized from iterable\'s items
            # (copied from class doc)
            """
            pass

        def __iter__(self): # real signature unknown; restored from __doc__
            """ x.__iter__() <==> iter(x) """
            pass

        def __len__(self): # real signature unknown; restored from __doc__
            """ x.__len__() <==> len(x) """
            pass

        def __le__(self, y): # real signature unknown; restored from __doc__
            """ x.__le__(y) <==> x<=y """
            pass

        def __lt__(self, y): # real signature unknown; restored from __doc__
            """ x.__lt__(y) <==> x<y """
            pass

        def __mul__(self, n): # real signature unknown; restored from __doc__
            """ x.__mul__(n) <==> x*n """
            pass

        @staticmethod # known case of __new__
        def __new__(S, *more): # real signature unknown; restored from __doc__
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass

        def __ne__(self, y): # real signature unknown; restored from __doc__
            """ x.__ne__(y) <==> x!=y """
            pass

        def __repr__(self): # real signature unknown; restored from __doc__
            """ x.__repr__() <==> repr(x) """
            pass

        def __reversed__(self): # real signature unknown; restored from __doc__
            """ L.__reversed__() -- return a reverse iterator over the list """
            pass

        def __rmul__(self, n): # real signature unknown; restored from __doc__
            """ x.__rmul__(n) <==> n*x """
            pass

        def __setitem__(self, i, y): # real signature unknown; restored from __doc__
            """ x.__setitem__(i, y) <==> x[i]=y """
            pass

        def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
            """
            x.__setslice__(i, j, y) <==> x[i:j]=y

                       Use  of negative indices is not supported.
            """
            pass

        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ L.__sizeof__() -- size of L in memory, in bytes """
            pass

        __hash__ = None


    </pre>
</details>

bool值

布尔值 只有True 和 False
真 1 True。
假 0 False。

>>> bool(42)
True
>>> bool()
False
>>>
bool
                class bool(int):
        """
        bool(x) -> bool

        Returns True when the argument x is true, False otherwise.
        The builtins True and False are the only two instances of the class bool.
        The class bool is a subclass of the class int, and cannot be subclassed.
        """
        def __and__(self, *args, **kwargs): # real signature unknown
            """ Return self&value. """
            pass

        def __init__(self, x): # real signature unknown; restored from __doc__
            pass

        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass

        def __or__(self, *args, **kwargs): # real signature unknown
            """ Return self|value. """
            pass

        def __rand__(self, *args, **kwargs): # real signature unknown
            """ Return value&self. """
            pass

        def __repr__(self, *args, **kwargs): # real signature unknown
            """ Return repr(self). """
            pass

        def __ror__(self, *args, **kwargs): # real signature unknown
            """ Return value|self. """
            pass

        def __rxor__(self, *args, **kwargs): # real signature unknown
            """ Return value^self. """
            pass

        def __str__(self, *args, **kwargs): # real signature unknown
            """ Return str(self). """
            pass

        def __xor__(self, *args, **kwargs): # real signature unknown
            """ Return self^value. """
            pass

    </pre>
</details>

字典

创建
d = {key1 : value1, key2 : value2 }

person = {"name": "Ycj", \'age\': 18}

person = dict({"name": "Ycj", \'age\': 18})
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组

# dict
d = {"a": "b", "b": "c"}
print(d["a"])  # b
d["a"] = d["a"] + "ddd"
print(d["a"])  # bddd

d = {}  # 创建字典1
d_ = dict()  # 创建字典1
d_["name"] = "A"  # 添加元素
d_["age"] = 12
print(d_)  # {\'name\': \'A\', \'age\': 12}
d[123] = 4556
print(d)

rec = {"name": {"first_name": "Bob", "last_name": "Smith"},
       "age": {"first_age": 1, "last_age": 2},
       # "work": {"first_work": "programmer", "last_work": "farmer"},
       "job":["dev", "mgr"]
       }
print(rec["name"])  # {\'first_name\': \'Bob\', \'last_name\': \'Smith\'}

rec["job"].append("janiter")
print(rec["job"])  # [\'dev\', \'mgr\', \'janiter\']

d = {chr(i): i for i in range(79, 85)}  # {\'O\': 79, \'P\': 80, \'Q\': 81, \'R\': 82, \'S\': 83, \'T\': 84}
ks = list(d.keys())  # [\'O\', \'P\', \'Q\', \'R\', \'S\', \'T\']
for key in list(d.keys()):

     print(key, "->", d[key])

for c in "ABC":
     # print(c.upper())  # 转换为大写 A B C
     print(c.lower())

# x = 4
# while x > 0:
#      print("spam" * x)
#      x-=1
x = 1
while x <= 4:
     print("spam" * x)
     x += 1

squares = [x ** 2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

li_data = list()

for i in range(10):
     li_data.append(i ** 3)
print(li_data)  # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

d = {chr(i): i for i in range(79, 85)}  # {\'O\': 79, \'P\': 80, \'Q\': 81, \'R\': 82, \'S\': 83, \'T\': 84}

d["add_data"] = "data"  # {\'O\': 79, \'P\': 80, \'Q\': 81, \'R\': 82, \'S\': 83, \'T\': 84, \'add_data\': \'data\'}

print("add_data" in d)  # True
print("add_data" not in d)  # False
dict
                    class dict(object):
            """
            dict() -> new empty dictionary
            dict(mapping) -> new dictionary initialized from a mapping object\'s
                (key, value) pairs
            dict(iterable) -> new dictionary initialized as if via:
                d = {}
                for k, v in iterable:
                    d[k] = v
            dict(**kwargs) -> new dictionary initialized with the name=value pairs
                in the keyword argument list.  For example:  dict(one=1, two=2)
            """
        def clear(self): # real signature unknown; restored from __doc__
            """ 清除内容 """
            """ D.clear() -> None.  Remove all items from D. """
            pass

        def copy(self): # real signature unknown; restored from __doc__
            """ 浅拷贝 """
            """ D.copy() -> a shallow copy of D """
            pass

        @staticmethod # known case
        def fromkeys(S, v=None): # real signature unknown; restored from __doc__
            """
            dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
            v defaults to None.
            """
            pass

        def get(self, k, d=None): # real signature unknown; restored from __doc__
            """ 根据key获取值,d是默认值 """
            """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
            pass

        def has_key(self, k): # real signature unknown; restored from __doc__
            """ 是否有key """
            """ D.has_key(k) -> True if D has a key k, else False """
            return False

        def items(self): # real signature unknown; restored from __doc__
            """ 所有项的列表形式 """
            """ D.items() -> list of D\'s (key, value) pairs, as 2-tuples """
            return []

        def iteritems(self): # real signature unknown; restored from __doc__
            """ 项可迭代 """
            """ D.iteritems() -> an iterator over the (key, value) items of D """
            pass

        def iterkeys(self): # real signature unknown; restored from __doc__
            """ key可迭代 """
            """ D.iterkeys() -> an iterator over the keys of D """
            pass

        def itervalues(self): # real signature unknown; restored from __doc__
            """ value可迭代 """
            """ D.itervalues() -> an iterator over the values of D """
            pass

        def keys(self): # real signature unknown; restored from __doc__
            """ 所有的key列表 """
            """ D.keys() -> list of D\'s keys """
            return []

        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

        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

        def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
            """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
            """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
            pass

        def update(self, E=None, **F): # known special case of dict.update
            """ 更新
                {\'name\':\'alex\', \'age\': 18000}
                [(\'name\',\'sbsbsb\'),]
            """
            """
            D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
            If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
            If E present and lacks .keys() method, 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

        def values(self): # real signature unknown; restored from __doc__
            """ 所有的值 """
            """ D.values() -> list of D\'s values """
            return []

        def viewitems(self): # real signature unknown; restored from __doc__
            """ 所有项,只是将内容保存至view对象中 """
            """ D.viewitems() -> a set-like object providing a view on D\'s items """
            pass

        def viewkeys(self): # real signature unknown; restored from __doc__
            """ D.viewkeys() -> a set-like object providing a view on D\'s keys """
            pass

        def viewvalues(self): # real signature unknown; restored from __doc__
            """ D.viewvalues() -> an object providing a view on D\'s values """
            pass

        def __cmp__(self, y): # real signature unknown; restored from __doc__
            """ x.__cmp__(y) <==> cmp(x,y) """
            pass

        def __contains__(self, k): # real signature unknown; restored from __doc__
            """ D.__contains__(k) -> True if D has a key k, else False """
            return False

        def __delitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__delitem__(y) <==> del x[y] """
            pass

        def __eq__(self, y): # real signature unknown; restored from __doc__
            """ x.__eq__(y) <==> x==y """
            pass

        def __getattribute__(self, name): # real signature unknown; restored from __doc__
            """ x.__getattribute__(\'name\') <==> x.name """
            pass

        def __getitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__getitem__(y) <==> x[y] """
            pass

        def __ge__(self, y): # real signature unknown; restored from __doc__
            """ x.__ge__(y) <==> x>=y """
            pass

        def __gt__(self, y): # real signature unknown; restored from __doc__
            """ x.__gt__(y) <==> x>y """
            pass

        def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
            """
            dict() -> new empty dictionary
            dict(mapping) -> new dictionary initialized from a mapping object\'s
                (key, value) pairs
            dict(iterable) -> new dictionary initialized as if via:
                d = {}
                for k, v in iterable:
                    d[k] = v
            dict(**kwargs) -> new dictionary initialized with the name=value pairs
                in the keyword argument list.  For example:  dict(one=1, two=2)
            # (copied from class doc)
            """
            pass

        def __iter__(self): # real signature unknown; restored from __doc__
            """ x.__iter__() <==> iter(x) """
            pass

        def __len__(self): # real signature unknown; restored from __doc__
            """ x.__len__() <==> len(x) """
            pass

        def __le__(self, y): # real signature unknown; restored from __doc__
            """ x.__le__(y) <==> x<=y """
            pass

        def __lt__(self, y): # real signature unknown; restored from __doc__
            """ x.__lt__(y) <==> x<y """
            pass

        @staticmethod # known case of __new__
        def __new__(S, *more): # real signature unknown; restored from __doc__
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass

        def __ne__(self, y): # real signature unknown; restored from __doc__
            """ x.__ne__(y) <==> x!=y """
            pass

        def __repr__(self): # real signature unknown; restored from __doc__
            """ x.__repr__() <==> repr(x) """
            pass

        def __setitem__(self, i, y): # real signature unknown; restored from __doc__
            """ x.__setitem__(i, y) <==> x[i]=y """
            pass

        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ D.__sizeof__() -> size of D in memory, in bytes """
            pass

        __hash__ = None

    dict

    </pre>
</details>

元组

创建
ages = (11, 22, 33, 44, 55)

ages = tuple((11, 22, 33, 44, 55))

# 元组(tuple)具有不变性(不能更改)


T = (1, 2, 3, 1)

print(len(T))  # 3
print(T + (1, 4, 5, 6))  # (1, 2, 3, 1, 4, 5, 6)
print(T.count(1))  # 2 统计个数
print(T.index(3))  # 索引 返回位置 2 在元组中没有 就会报错

# 混合类的类型的嵌套

T = ("spam", 3.0, [11, 22, 33])
print(T[0])  # spam
print(T[2][2])  # 33
# tuple中没有append(x)函数
# T.append(2) Error

tuple
            lass tuple(object):
                """
                tuple() -> empty tuple
                tuple(iterable) -> tuple initialized from iterable\'s items
            If the argument is a tuple, the return value is the same object.
            """
            def count(self, value): # real signature unknown; restored from __doc__
                """ T.count(value) -> integer -- return number of occurrences of value """
                return 0

            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

            def __add__(self, y): # real signature unknown; restored from __doc__
                """ x.__add__(y) <==> x+y """
                pass

            def __contains__(self, y): # real signature unknown; restored from __doc__
                """ x.__contains__(y) <==> y in x """
                pass

            def __eq__(self, y): # real signature unknown; restored from __doc__
                """ x.__eq__(y) <==> x==y """
                pass

            def __getattribute__(self, name): # real signature unknown; restored from __doc__
                """ x.__getattribute__(\'name\') <==> x.name """
                pass

            def __getitem__(self, y): # real signature unknown; restored from __doc__
                """ x.__getitem__(y) <==> x[y] """
                pass

            def __getnewargs__(self, *args, **kwargs): # real signature unknown
                pass

            def __getslice__(self, i, j): # real signature unknown; restored from __doc__
                """
                x.__getslice__(i, j) <==> x[i:j]

                           Use of negative indices is not supported.
                """
                pass

            def __ge__(self, y): # real signature unknown; restored from __doc__
                """ x.__ge__(y) <==> x>=y """
                pass

            def __gt__(self, y): # real signature unknown; restored from __doc__
                """ x.__gt__(y) <==> x>y """
                pass

            def __hash__(self): # real signature unknown; restored from __doc__
                """ x.__hash__() <==> hash(x) """
                pass

            def __init__(self, seq=()): # known special case of tuple.__init__
                """
                tuple() -> empty tuple
                tuple(iterable) -> tuple initialized from iterable\'s items

                If the argument is a tuple, the return value is the same object.
                # (copied from class doc)
                """
                pass

            def __iter__(self): # real signature unknown; restored from __doc__
                """ x.__iter__() <==> iter(x) """
                pass

            def __len__(self): # real signature unknown; restored from __doc__
                """ x.__len__() <==> len(x) """
                pass

            def __le__(self, y): # real signature unknown; restored from __doc__
                """ x.__le__(y) <==> x<=y """
                pass

            def __lt__(self, y): # real signature unknown; restored from __doc__
                """ x.__lt__(y) <==> x<y """
                pass

            def __mul__(self, n): # real signature unknown; restored from __doc__
                """ x.__mul__(n) <==> x*n """
                pass

            @staticmethod # known case of __new__
            def __new__(S, *more): # real signature unknown; restored from __doc__
                """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
                pass

            def __ne__(self, y): # real signature unknown; restored from __doc__
                """ x.__ne__(y) <==> x!=y """
                pass

            def __repr__(self): # real signature unknown; restored from __doc__
                """ x.__repr__() <==> repr(x) """
                pass

            def __rmul__(self, n): # real signature unknown; restored from __doc__
                """ x.__rmul__(n) <==> n*x """
                pass

            def __sizeof__(self): # real signature unknown; restored from __doc__
                """ T.__sizeof__() -- size of T in memory, in bytes """
                pass

    </pre>
</details>

也下是python的常见的内置函数

详细见python文档,猛击这里

文件操作

文件操作

  • 打开文件
  • 操作文件

打开文件

文件句柄 = file(\'文件路径\', \'模式\')

python中打开文件有两种方式,即:open(...) 和 file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open()

打开文件的模式有:

r,只读模式(默认)。
w,只写模式。【不可读;不存在则创建;存在则删除内容;】
a,追加模式。【可读; 不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

r+,可读写文件。【可读;可写;可追加】
w+,写读
a+,同a
"U"表示在读取时,可以将 \\r \\n \\r\\n自动转换成 \\n (与 r 或 r+ 模式同使用)

rU
r+U
**"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
**
rb
wb
ab
文件的常用的操作方法:
read(3):

  1. 文件打开方式为文本模式时,代表读取3个字符。

  2. 文件打开方式为b模式时,代表读取3个字节。

其余的文件内光标移动都是以字节为单位的如:seek,tell,truncate。

注意:

  1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的。

  2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果。

基本操作

# # 写模式 w  会把原先的内容清空 在写入
# f = open(\'log.txt\', mode="w", encoding="utf-8")  # open默认的读模式
# f.write("hello 你好!")  # 读文件
# f.close()

# 写模式 wb 二进制文件  会把原先的内容清空 在写入
#
# f = open(\'log.txt\', mode=\'wb\')  # 就不需要encoding(编码)
# f.write("This is test".encode("utf-8"))  # 编码成utf-8
# f.close()

# # 读 r模式
# f = open("log.txt", mode=\'r\', encoding="utf-8")
# print(f.read())  # hello 你好!
# f.close()
#
# 读 rb模式
# f = open("log.txt", mode=\'rb\')
# # print(f.read())  # b\'This is test\'
# # f.close()

# 追加 a模式 在原先的内容后面添加数据

# f = open("log.txt", mode=\'a\', encoding=\'utf-8\')
# f.write("中国")   # 原先的log.txt文件的内容是 This is test  现在的内容是:This is test中国
# f.close()

# 追加 ab模式 在原先的内容后面添加数据
# f = open("log.txt", mode=\'ab\')
# f.write(\'我\'.encode(\'utf-8\'))  # This is test中国我
# f.close()

# # r+ 读写
# f = open(\'log.txt\', mode=\'r+\', encoding=\'utf-8\')
# print(f.read()) # XXXXXXXXXXXXXXXXXX
# f.write("aaa")
# f.seek(0)
# print(f.read())  # XXXXXXXXXXXXXXXXXXaaa
# f.close()

# # w+ 写读

# f = open(\'log.txt\', mode=\'w+\', encoding=\'utf-8\')
# f.write(\'中国\')
# f.seek(0)  # 把光标移到收位置 光标是按照字节数来索引  中文是3的倍数,中文一个字占3个字节
# print(f.read()) # 中国


# 读文件

# FileRead = open("log.txt", \'r\', encoding=\'utf-8\')
# for lines in FileRead.readlines():  # readlines 全部读取保存在列表中
#     print("lines:", lines.strip(\'\\n\'))
# FileRead.close()

# FileRead = open("log.txt", \'r\', encoding=\'utf-8\')
# print(FileRead.readline().strip(\'\\n\'))  # 一行一行读取   中国
# print(FileRead.readline().strip(\'\\n\'))               # 北京
# print(FileRead.readline().strip(\'\\n\'))               # 上海
#
# FileRead.close()
# FileRead = open("log.txt", \'r\', encoding=\'utf-8\')
# print(FileRead.tell())  # tell 返回光标的位置  0
# FileRead.close()

# 
# FileRead = open("log.txt", \'a+\', encoding=\'utf-8\')   # 文件内容:abcdefghijklmn
# FileRead.truncate(4)   # 文件内容:abcd  截取了4个字符保留
# FileRead.close()

文件的修改

方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,
再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)

"""
# log.txt文件内容
中国
北京
上海
天津
"""
import os
with open(\'log.txt\', mode=\'r\',  encoding=\'utf-8\') as read_f, open(\'log.bak\', mode=\'w\', encoding=\'utf-8\') as write_f:
    data = read_f.read()
    data = data.replace(\'北京\', \'beijing\')
    write_f.write(data)
    

os.remove(\'log.txt\')  # 删除原来的文件
os.rename(\'log.bak\', \'log.txt\')  # 对改过的文件,进行重新命名

"""
中国
beijing
上海
天津
"""

方式二:将硬盘存放的该文件的内容一行一行地读入内存,
修改完毕就写入新文件,最后用新文件覆盖源文件。

"""
# log.txt文件内容
中国
北京
上海
天津
"""
import os
with open(\'log.txt\', mode=\'r\',  encoding=\'utf-8\') as read_f, open(\'log.bak\', mode=\'w\', encoding=\'utf-8\') as write_f:
    for line in read_f:
        if \'北京\' in line:
            line = line.replace("北京", \'beijing\')
        write_f.write(line)
        
os.remove(\'log.txt\')  # 删除原来的文件
os.rename(\'log.bak\', \'log.txt\')  # 对改过的文件,进行重新命名
"""
中国
beijing
上海
天津
"""

test:

文件a内容:每一行内容分别为商品名字,价钱,个数。

apple 10 3

tesla 100000 1

mac 3000 2

lenovo 30000 3

chicken 10 3

通过代码,将其构建成这种数据类型:[{\'name\':\'apple\',\'price\':10,\'amount\':3},{\'name\':\'tesla\',\'price\':1000000,\'amount\':1}......] 并计算出总价钱。

def deal_file(dir_=\'log.txt\'):
    with open(dir_, \'r\', encoding=\'utf-8\') as f:
            list_ = f.readlines()
            res_list = []
            for i in range(0, len(list_), 2):
                    res_list.append(list_[i].strip().split())

            res_tuple = []
            d = dict()
            for i in range(len(res_list)):
                d = {"name": res_list[i][0], "price": res_list[i][1], "amount": int(res_list[i][2])}

                res_tuple.append(d)

            sum = 0
            for i in res_tuple:

                sum += int(i[\'price\']) * int(i[\'amount\'])

            print("sum:", sum)
            print(res_tuple)


deal_file()
#________________________________
sum: 196060
[{\'name\': \'apple\', \'price\': \'10\', \'amount\': 3}, {\'name\': \'tesla\', \'price\': \'100000\', \'amount\': 1}, {\'name\': \'mac\', \'price\': \'3000\', \'amount\': 2}, {\'name\': \'lenovo\', \'price\': \'30000\', \'amount\': 3}, {\'name\': \'chicken\', \'price\': \'10\', \'amount\': 3}]


file操作函数
			class file(object):
def close(self): # real signature unknown; restored from __doc__
    关闭文件
    """
    close() -> None or (perhaps) an integer.  Close the file.
     
    Sets data attribute .closed to True.  A closed file cannot be used for
    further I/O operations.  close() may be called more than once without
    error.  Some kinds of file objects (for example, opened by popen())
    may return an exit status upon closing.
    """
 
def fileno(self): # real signature unknown; restored from __doc__
    文件描述符  
     """
    fileno() -> integer "file descriptor".
     
    This is needed for lower-level file interfaces, such os.read().
    """
    return 0    
 
def flush(self): # real signature unknown; restored from __doc__
    刷新文件内部缓冲区
    """ flush() -> None.  Flush the internal I/O buffer. """
    pass








def isatty(self): # real signature unknown; restored from __doc__
    判断文件是否是同意tty设备
    """ isatty() -> true or false.  True if the file is connected to a tty device. """
    return False

def next(self): # real signature unknown; restored from __doc__
    获取下一行数据,不存在,则报错
    """ x.next() -> the next value, or raise StopIteration """
    pass
 
def read(self, size=None): # real signature unknown; restored from __doc__
    读取指定字节数据
    """
    read([size]) -> read at most size bytes, returned as a string.
     
    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.
    """
    pass
 
def readinto(self): # real signature unknown; restored from __doc__
    读取到缓冲区,不要用,将被遗弃
    """ readinto() -> Undocumented.  Don\'t use this; it may go away. """
    pass
 
def readline(self, size=None): # real signature unknown; restored from __doc__
    仅读取一行数据
    """
    readline([size]) -> next line from the file, as a string.
     
    Retain newline.  A non-negative size argument limits the maximum
    number of bytes to return (an incomplete line may be returned then).
    Return an empty string at EOF.
    """
    pass
 
def readlines(self, size=None): # real signature unknown; restored from __doc__
    读取所有数据,并根据换行保存值列表
    """
    readlines([size]) -> list of strings, each a line from the file.
     
    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.
    """
    return []
 
def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
    指定文件中指针位置
    """
    seek(offset[, whence]) -> None.  Move to new file position.
     
    Argument offset is a byte count.  Optional argument whence defaults to
    0 (offset from start of file, offset should be >= 0); other values are 1
    (move relative to current position, positive or negative), and 2 (move
    relative to end of file, usually negative, although many platforms allow
    seeking beyond the end of a file).  If the file is opened in text mode,
    only offsets returned by tell() are legal.  Use of other offsets causes
    undefined behavior.
    Note that not all file objects are seekable.
    """
    pass
 
def tell(self): # real signature unknown; restored from __doc__
    获取当前指针位置
    """ tell() -> current file position, an integer (may be a long integer). """
    pass
 
def truncate(self, size=None): # real signature unknown; restored from __doc__
    截断数据,仅保留指定之前数据
    """
    truncate([size]) -> None.  Truncate the file to at most size bytes.
     
    Size defaults to the current file position, as returned by tell().
    """
    pass
 
def write(self, p_str): # real signature unknown; restored from __doc__
    写内容
    """
    write(str) -> None.  Write string str to file.
     
    Note that due to buffering, flush() or close() may be needed before
    the file on disk reflects the data written.
    """
    pass
 
def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
    将一个字符串列表写入文件
    """
    writelines(sequence_of_strings) -> None.  Write the strings to the file.
     
    Note that newlines are not added.  The sequence can be any iterable object
    producing strings. This is equivalent to calling write() for each string.
    """
    pass
 
def xreadlines(self): # real signature unknown; restored from __doc__
    可用于逐行读取文件,非全部
    """
    xreadlines() -> returns self.
     
    For backward compatibility. File objects now include the performance
    optimizations previously implemented in the xreadlines module.
    """
    pass

</pre>

格式化的输出(%s、format)


print("This is %s" % "test")  # This is test
print("%s , %d , %s" % (\'a\', 12, \'b\'))  # a , 12 , b
print(\'3%% %s\' % "abc")  # 显示%号

str_ = \'\'\'
	a b c d %s
	  a b c %s
	    a b %s
	      a %s
	        %s
	\'\'\' % ("e", "d", "c", "b", "a")


# a b c d e
#   a b c d
#     a b c
#       a b
#         a

# format() 输出

# 位置显示
\'a1 ={}, a2={}, a3={}\'.format("1", "2", "3")     # a1 =1, a2=2, a3=3
\'a1 ={1}, a2={2}, a3={0}\'.format("1", "2", "3")     # a1 =2, a2=3, a3=1

"Your name is{name}, age is {age}".format(name="A", age=12)  # Your name isA, age is 12
"Your name is{name}, age is {age}".format(age=12, name="A")  # Your name isA, age is 12 和位置无关
# 对象的的属性

class A:
    def __init__(self, name, age):  # 构造函数
        self.name = name
        self.age = age


        P = A("B", 18)
        "name is: {p.name}, age is:{p.age}".format(p=P) # name is: B, age is:18

# 通过下标
s1 = [1, "23", "S"]
s2 = ["s2.1", "s2.2", "s2.3"]

\'{0[1]}  {0[2]} {1[2]} {1[0]}\'.format(s2, s1)  # s2.2  s2.3 S 1

# 格式化输出

a = \'[{:<10}]\'.format(\'12\')  # 默认填充空格的  输出左对齐定长为10位 [12        ]
b = "[{:>10}]".format("abc")  # 默认填充空格的  输出左对齐定长为10位 [       abc]
c = "[{:*>10}]".format("abc")  # 输出左对齐定长为10位 填入一个ascii字符  [*******abc]
d = "[{:*<10}]".format("abc")  # 输出右对齐定长为10位 填入一个ascii字符  [abc*******]
e = "[{:*^10}]".format("abc")  # 输出居中对其为10位 填入一个ascii字符  [***abc****]


# 浮点小数输出
import math
a1 = "{:.6f}".format(math.pi) # 3.141593     通常都是配合 f 使用,其中.2表示长度为2的精度,f表示float类型

a2 = "{:,}".format(12345945852326.1524512345)  # 12,345,945,852,326.152

# 进制及其他显示

    \'\'\'
b : 二进制
d :十进制
o :八进制
!s :将对象格式化转换成字符串
!a :将对象格式化转换成ASCII
!r :将对象格式化转换成repr
\'\'\'
    b1 = \'{:b}\'.format(10)  #二进制 :1010
    b2 = \'{:d}\'.format(10)  # 10进制 :10
    b3 = \'{:o}\'.format(45)  # 8进制 :55
    b4 = \'{:x}\'.format(45)  # 16进制 :2d
    b5 = \'{!s}\'.format(\'45\')  # 45
    b6 = "{!a}".format("10")  # \'10\'
    b7 = "{!r}".format("10")  # \'10\'
    print(b7)

其他的类型

x = set("spam")

y = {"h", "a", "m"}

print(x & y)  # 与 {\'m\', \'a\'}
print(x | y)  # 或 {\'p\', \'m\', \'s\', \'h\', \'a\'}
print(x - y)  # {\'p\', \'s\'}
print(y - x)  # {\'h\'}

print(1/3)  # 0.3333333333333333
import decimal
d = decimal.Decimal("3.14")
d = d + 12
print(d)  # 15.14


from fractions import Fraction  # 转换为分式
f = Fraction(2, 3)  # 2/3
f = f + 1  # 5/3
f_ = f + Fraction(10, 27)
print(f_)  # 55/27

python内置函数

str(字符串)

str_ = "abc\\tdefghAa"
print(str_.capitalize())  # Abcdefgh
print(str_.center(20, "_"))  # ______abcdefgh______
print(str_.count("a"))   # 2
print(str_.endswith("b"))  # 也什么结尾
print(str_.startswith("a"))  # 也什么开始
print(str_.lower())  # 全部变成小写
print(str_.upper())  # 全部变成大写
print(str_.index("a"))  # 索引 没有报错 0
print(str_.find("d"))  # 索引 没有不报错 3
print(str_.rfind("a"))
print(str_.casefold())  # abcdefgha 和lower类似
print(str_.encode())  # 回编码后的字符串 b\'abcdefghAa\'
print(str_.isalnum())  # True 所有字符都是字母数字,则返回 True
print(str_.expandtabs())  # abc     defghAa 遇见\\t,\\t前面的字符站8个字符,默认 如果没有没有8个字符,填空格
print(str_.isdecimal())  # 全部是10进制, 返回true
print(str_.isprintable())   # False 判断是否为可打印字符串
print(str_.islower())  # False 有大小写字母都是小写字母,则返回True
print(str_.isspace())  # answer: False 所有字符都是空格,则返回True
print(str_.isdigit())  # answer: False 所有字符都是数字,则返回True
print(str_.isalpha())  # answer:False 所有字符都是字母,则返回True
print(str_.isupper())  # answer:False 所有的字符是大写 ,则返回True
print(str_.istitle())  # answer:False 字符串的所有的单词的首字母,是否为大写,其他的是否小写,则返回True ,for example:"Title"
print(str_.isidentifier()) # answer:False 如果S是一个有效的标识符,返回True ;for example :"data".isindentifier() return True
str_data = ("a", "b", "c")
print("-".join(str_data))  # answer: a-b-c 序列中的元素以指定的字符连接生成一个新的字符串。
print("-".join(str_))  # answer: -d-e-f-g-h-A-a
str_ = "abc\\tdefghAa"
print(str_.swapcase())  # 将大写字符转换为小写(小变大,大变小)  ABC	DEFGHaA

str_data = "abcdef"
print(str_data.zfill(10))  # 0000abcdef 填充一个左边为0的数字字符串S
str_data = "   abcfe    "
print(str_data.lstrip())  # answer:abcfe  返回去掉前导空格的字符串S的副本。如果字符是给定的而不是空字符,则删除字符中的字符。
str_ = "abc\\tdefghAa"
print(str_.rsplit())  # answer:[\'abc\', \'defghAa\'] 指定分隔符对字符串进行切片,如果参数 num 有指定值
print(str_data.strip())    # 去除左右空格
print(str_data.rstrip())  # answer:   abcfe 去除右空格
print(str_.ljust(20, "*"))  # answer:abc	defghAa********* 右填充"char" len 20 以Unicode长宽度字符串返回左对齐。填充使用指定的填充字符完成(默认为空格)。
print(str_.rjust(20), "^")  # answer:          abc	defghAa ^, 返回右对齐的长度宽度字符串。填充使用指定的填充字符完成(默认为空格)。
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab) # 简单理解是替换
print(trantab)  # {97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
str = "this is string example....wow!!!"
print (str.translate(trantab))  # th3s 3s str3ng 2x1mpl2....w4w!!!
print(str_.splitlines())  # answer:[\'abc\\tdefghAa\']   返回S中的行列表,在行边界处断开。
print(str_.replace("a", "v")) # vbc	defghAv 替换a -> v
test = "abcdefgh"
print(test.partition("d"))  # 分割 (\'abc\', \'d\', \'efgh\') 搜索S中的sep分隔符,返回之前的部分
print(test.rpartition("a"))  # (head, sep, tail)->(\'\', \'a\', \'bcdefgh\')
print(test.zfill(20))  # answer: 000000000000abcdefgh 返回长度为width的字符,源字符string右对齐,前面填0

dict(字典)

d = {"a": "A", "b": "B", "c": "C"}
print(list(d.keys()))  # answer: [\'a\', \'b\', \'c\']  返回键key
print(list(d.values()))  # answer: [\'A\', \'B\', \'C\'] 返回值values
# print(d.clear())    # answer: None  中删除(清除)所有项目

print(d.copy())  # 拷贝 和原数据一模一样
d_ = d.copy()
print(d_)  # {\'a\': \'A\', \'b\': \'B\', \'c\': \'C\'}

print(d.fromkeys("A", "xx"))  # answer:{\'A\': \'xx\'} 返回一个新的字典,其中键来自iterable,值等于值
x = ("goole", "apple", "sony")
print(d.fromkeys(x, 1))  # {\'goole\': 1, \'apple\': 1, \'sony\': 1}

print(d.get("a"))  # answer: A ; 通过key -> values 没有key 返回None
# print(d.pop("a"))  # 删除 a的键和值
print(d)  # {\'b\': \'B\', \'c\': \'C\'}

print(list(d.items()))  # 返会key和values 也元组的形式出现 [(\'b\', \'B\'), (\'c\', \'C\')]
print(d.popitem())   # 删除item 默认是从后面删除
print(d)   # {\'a\': \'A\', \'b\': \'B\'}


print(d.setdefault("A"))  # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D 如果key存在,返回key,
# 否则创建字典{key:None}创建key是你查询的key
print(d)  # {\'a\': \'A\', \'b\': \'B\', \'A\': None}
d = {"a": "A", "b": "B", "c": "C"}
d1 = {"xxx": "test"}
d.update(d1)  # 会对原数据进行修改 将d1的数据加入d中
print(d)  # {\'a\': \'A\', \'b\': \'B\', \'c\': \'C\', \'xxx\': \'test\'}

list(列表)

list_ = [1, "a", "v", 4153.01]
print(list_.pop(0))  # 删除list_[0]元素
print(list_)  # [\'a\', \'v\', 4153.01]
b = list_.copy()  # 拷贝  [\'a\', \'v\', 4153.01]
print(b)

# print(list_.clear())  # 删除(清除)列表
# print(list_)  # [] 空列表
# list_ = [\'a\', \'v\', 4153.01]
print(list_.index("v", 0, 5))  # L.index(value, [start, [stop]]) -> integer -- return first index of value.
# 返回第一个索引值  answer: 1

print(list_.count("x"))  # count统计个数 answer: 0
print(list_.append("x"))  # 在list尾部添加元素
print(list_)  # [\'a\', \'v\', 4153.01, \'x\']
list_.reverse()  # 反转(前后替换)
print(list_)

# list.sort(cmp=None, key=None, reverse=False) reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)
test = ["google", "facebook", "123"]
t = [1, 99, 12, 45]
t.sort(reverse=True)  # [99, 45, 12, 1] 降序
test.sort(reverse=False)  # 升序 [\'123\', \'facebook\', \'google\']
print(test)
print(t)

list_= [\'x\', 4153.01, \'v\', \'a\']
list_.remove("a")
print(list_)  # 移除 [\'x\', 4153.01, \'v\']

# extend() 函数用于在列表末尾一次性追加另一个序列中的多个值
list_.extend(["u", "f"])  # L.extend(iterable) -> None -- extend list by appending elements from the iterable
print(list_)  # [\'x\', 4153.01, \'v\', \'u\', \'f\']
list_.insert(1, "name")  # 插入 在第一个位置插入"name" [\'x\', \'name\', 4153.01, \'v\', \'u\', \'f\']

set(集合)

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort

使用 Python 代码片段编写 LaTeX 文档

python 机器学习有用的代码片段

python 代码片段和解决方案

python 来自puddletag的代码片段