[笔记]Python为舟

Python是一门非常简单的编程语言,简单但是用到实际的地方是比较多的,比如机器学习和web编程,以及网络爬虫和一些简单的辅助性脚本等,本文着重总结小东在学习Python过程中没注意到的或者觉得比较重要的知识点。

Python

Python is powerful... and fast;
plays well with others;
runs everywhere;
is friendly & easy to learn;
is Open.

0x01 数组初始化

快速初始化一个数组

arr = [0 for i in range(0,10)]
arr = [0]*10
# 二维数组
matrix = [[0]*10]*10

0x02 保留字

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> len(keyword.kwlist)
33

\ 多行换行时结尾使用反斜杠,TrueFalse的值为1和0

0x03 数字

int在py3中为长整型,在整除运算中//即可实现结果为整数(向下取整,math.ceil(x)可以实现向上取整),幂(10**3,即10的3次方)。

>>> import math
>>> a = 5.5
>>> math.floor(a)
5
>>> math.ceil(a)
6
>>>

0x04 字符串

字符串使用的时候使用’’,””,来包裹,\用于转义,如果要使\不被转义,则加上r'这是字符串 \n'

>>> s = r"hello \n"
>>> s
'hello \\n'
>>> print(s)
hello \n
>>> t = 'hello \n'
>>> print(t)
hello

>>> s = 'admin'*2
>>> s
'adminadmin'
>>>
>>> s = '123'; t = '456'; u = s+t;print(u)        # 单行;分割
123456

0x05 print

print() 默认会换行,不换行的方法:print(x, end='')

>>> y='b';print(x, end='');print(y, end='')
ab

0x06 多变量复制

>>> a,b,c = 'a','bb','ccc'
>>> print(a+b+c)
abbccc

0x07 type与isinstance

isinstance认为子类和父类是同一类,type相反

>>> class A:
...     pass        # 在Python中 pass 用于占位,一般用于一个函数还未想好写函数体的时候用于占位测试,避免编译错误
...
>>> class B(A):
...     pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False

0x08 del

del 用于删除一些对象引用、对象

0x09 list 列表

list列表类似与string类型,其次list中的数据类型可以不同,很强大。其中可以接受三个参数list[1:10:2],第三个参数是步长,输出1,3,5,7,9

>>> arr = [i for i in range(10)]
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr[1:9:2]
[1, 3, 5, 7]
>>> arr[0:9:2]
[0, 2, 4, 6, 8]
>>> arr[::2]
[0, 2, 4, 6, 8]
>>> arr[-2]
8
>>> arr[1-2]
9
>>> arr[-1]
9
>>> arr[1::2]
[1, 3, 5, 7, 9]
>>>

元祖(tuple)与列表类似,但是元祖的值无法改变,但是可以包含list类型的可变对象,初始空元祖tuple(),初始一个元素的元祖tuple(1,)有一个,

string、list 和 tuple 都属于 sequence(序列),均可以使用+实现拼接

0x10 set 集合

集合初始化 {val1, val2,...},空集合a = set(),若直接使用{}则初始的是一个字典,集合可以使用集合运算

>>> a = set('abracadabra')        # 集合初始化会自动剔除重复字符
>>> b = set('alacazam')
>>> a
{'c', 'r', 'b', 'd', 'a'}
>>> b
{'c', 'z', 'm', 'l', 'a'}
>>> a-b                            # a有b没有,差集
{'r', 'b', 'd'}
>>> a|b                            # a与b的并集
{'c', 'r', 'z', 'b', 'm', 'd', 'l', 'a'}
>>> a&b                            # a与b的交集
{'c', 'a'}
>>> a^b                            # a与b的异或,a和b各自拥有的
{'r', 'd', 'z', 'l', 'b', 'm'}
>>>

0x11 字典 {}

字典是一个键值对类型的,其属性和值都是支持多变量类型

>>> dic = {'name':'dyboy','sex':'boy','age':20}
>>> dic['name']
'dyboy'
>>> dic
{'name': 'dyboy', 'sex': 'boy', 'age': 20}
>>> dic.keys()
dict_keys(['name', 'sex', 'age'])
>>> dic.values()
dict_values(['dyboy', 'boy', 20])
>>>dict(a=1,b=2,c=3)                # 必须是一个序列 (key,value)元组
{'a': 1, 'b': 2, 'c': 3}
>>>frozenset(dic)                    # 转变为不可变的集合
>>>

0x12 eval()函数

eval能够计算参数中有效的计算表达式,并返回结果

0x13 几个字符操作函数

函数名 功能
chr(x) 将一个 整数 转换为 字符
ord(x) 将一个字符 转换为 整数
hex(x) 将一个 整数 转换为 16进制字符串
oct(x) 将一个 整数 转换为 8进制字符串
bin(x) 将一个 整数 转换为 2进制字符串
>>> x=10
>>> chr(x)
'\n'
>>> hex(x)
'0xa'
>>> oct(x)
'0o12'
>>> bin(x)
'0b1010'
>>> ord('a')
97
>>>

0x14 id() 函数

返回对象的内存地址id([object])

0x15 is, is not与 ==

s 用于判断两个变量引用对象是否为同一个,== 用于判断引用变量的值是否相等。

is not 判断两个变量引用的对象是否不是同一个

0x16 round()

round(a [, b]),浮点数求四舍五入,第二个参数为要留下小数部分的位数

>>> round(1.52)
2
>>> a = 1.523
>>> round(a)
2
>>> round(a, 1)
1.5
>>> round(a, 2)
1.52
>>> b = 1.000056
>>> round(b, 5)
1.00006
>>> round(b, 3)
1.0
>>>

0x17 三引号

三引号能够实现所见即所得模式,避免复杂的转义工作

0x18 大小写转换

字符串大小写转换操作

>>> ss = 'admin'
>>> ss.upper()
'ADMIN'
>>> tt = ss.upper()
>>> tt
'ADMIN'
>>> tt.lower()
'admin'
>>> tt.swapcase()
'admin'
>>>

0x19 替换字符串

string.replace(old, new [, max])max指定最大可替换的次数,默认全部替换

>>> ss = 'sdhhdhd'
>>> ss.replace('h','a')
'sdaadad'

0x20 zfill()

string.zfill(width),返回长度为 width 的字符串,原字符串右对齐,前面填充 0

0x21 isdecimal()

返回真假,字符串中是否是十进制的数字

0x22 list的函数

copy 函数与 = 赋值的区别在于引用源是否一致,copy等同于new一个list

>>> l= [1,2,3]
>>> a = l
>>> a
[1, 2, 3]
>>> b = l.copy()
>>> id(b)
2328445122312
>>> id(l)
2328445218888
>>> id(a)
2328445218888

list.reverse(),反向某列表

list.remove(value),移除列表中首个值为value的元素

list.sort( key=None, reverse=False),对列表进行排序

list.append(val),追加元素val到列表末尾

list.clear(),清空列表

list.index(obj),索引obj的第一次出现的为止

list.count(obj),返回obj出现在列表中的次数

list.pop(index = 1),删除值,并返回值,默认索引为末尾

0x23 连续赋值

a, b = b, a+b,赋值的顺序是从右往左,换句话说,右边的变量值都不会改变,即使发生运算

0x24 迭代器

ii = iter(list)next(ii)访问输出下一个元素,这是迭代器的两个方法,字符串、list 和元组都可以 iter()

0x25 生成器 generator

每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。使用了 yield函数被称为生成器(generator),生成器是一个返回迭代器的函数,只能用于迭代操作

import sys

def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n):
            return
        yield a                    # yiled
        a, b = b, a + b
        counter += 1

f = fibonacci(10) # f 是一个迭代器,由生成器返回生成

while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()

0x26 变量

类型属于对象,变量没有类型,是对象的一个引用

0x27 预定义变量

>>> import builtins as bu
>>> print(bu)
<module 'builtins' (built-in)>
>>> dir(bu)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>>

0x28 数据结构

堆栈可使用 listappend()pop()函数

0x29 字典遍历

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)                        # 可打印字典中的key+value

0x30 zip()

zip函数将可迭代对象作为参数,打包成为元组组成zip对象,然后返回一个可迭代的zip对象

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> zip(a,b)
<zip object at 0x00000288CA3596C8>
>>> c = zip(a,b)
>>> c
<zip object at 0x00000288CA39E688>
>>> for i in c:
    print(i)


(1, 4)
(2, 5)
(3, 6)
>>>

矩阵的行列变换用法:

>>> l1=[[1,2,3],[4,5,6],[7,8,9]]
>>> print([[j[i] for j in l1] for i in range(len(l1[0])) ])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> zip(*l1)
<zip object at 0x7f5a22651f88>
>>> for i in zip(*l1):
        print(i)

(1, 4, 7)
(2, 5, 8)
(3, 6, 9)

0x31 * ** ***

加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。**参数会以字典传入。如果单独出现星号 * 后的参数必须用关键字传入

0x32 shell交互

CMD shell下我们一般运行python程序,就需要sys包中argv参数

import sys

if __name__ == '__main__':
    print("输入的参数:" ,end="")
    for i in sys.argv:                    # 第一个是文件名,之后是参数...
        print(i)
print(sys.path)                            # 运行脚本的路径

0x33 import 包

模块(import)每个模块都有一个__name__属性,当其值是__main__时,表明该模块自身在运行,否则是被引入

查看包内容,可以使用内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回!

0x34 文件

open(filename [, mode]),返回一个file对象

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

打开文件的模式

0x35 发送邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host="smtp.XXX.com"  #设置服务器
mail_user="XXXX"    #用户名
mail_pass="XXXXXX"   #口令
sender = 'test@test.com'        # 比如网易邮箱,设置SMTP服务后,填写到上面配置信息
receivers = ['dyboy2017@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('<h1>Python 邮件发送测试...</h1>', 'html', 'utf-8')
message['From'] = Header("DYBOY", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")

0x36 类方法

构造方法

def __init__(self):
    self.name = 'Anonymous

在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例

如果在子类中需要父类的构造方法就需要显式地调用父类的构造方法,或者不重写父类的构造方法。子类不重写 __init__,实例化子类时,会自动调用父类定义的 __init__。重写时,使用super(子类,self).__init__(参数1,参数2,....)

使用 __两个下划线开头,定义私有变量和私有方法。私有变量只能在类中访问self.__param_1,私有方法只能在类内部调用

0x37 or and not

优先级顺序:or < and < not

0x38 json数据

json数据编码:json.dumps()

json数据解码:json.loads()

0x39 时间

>>> import time

>>> time.time()                                                        # 当前时间戳
1551273585.3901644

>>> time.localtime(time.time())
time.struct_time(tm_year=2019, tm_mon=2, tm_mday=27, tm_hour=21, tm_min=20, tm_sec=14, tm_wday=2, tm_yday=58, tm_isdst=0)

>>> time.asctime(time.localtime(time.time()))                        # 读取时间
'Wed Feb 27 21:20:40 2019'

>>> time.localtime()                                                # 本地时间
time.struct_time(tm_year=2019, tm_mon=2, tm_mday=27, tm_hour=21, tm_min=21, tm_sec=58, tm_wday=2, tm_yday=58, tm_isdst=0)

>>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())                # 时间格式化输出
'2019-02-27 21:23:40'

>>> now = time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())    # 转字符串
>>> now
'Wed Feb 27 21:24:23 2019'

>>> time.mktime(time.strptime(now, "%a %b %d %H:%M:%S %Y"))            # 字符串转时间戳
1551273863.0
>>>
`

0x40 日历

这个模块就很神奇了!

>>> import calendar
>>> cal = calendar.month(2018,2)
>>> cal
'   February 2018\nMo Tu We Th Fr Sa Su\n          1  2  3  4\n 5  6  7  8  9 10 11\n12 13 14 15 16 17 18\n19 20 21 22 23 24 25\n26 27 28\n'
>>> print(cal)
   February 2018
Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28

>>>

0x41 总结

差不多把自己不熟悉或者没咋记住的内容重新整理一遍,虽然还有一些类似内置函数,hash()bytes()等等,不是比较常用的内容,暂时不用过于记忆。编程语言只是一门语言,只是实现程序的一个基础,程序的核心级价值所在应当是算法,算法是程序的灵魂,编程语言是载体。

发表评论 / Comment

用心评论~


Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23