python 入门

2020-02-15  本文已影响0人  Robin92

(看了一个入门课程,整理到这里)

通用

变量类型

string

math 包

bool

list

tuple 元组

dict 字典

条件判断

if condition:
    do_somethind()
elif condition:
    do_somethind()
else:
    do_something()

循环

for elem in li:
    do_something()

while condition:
    do_something()

函数

def func_name(variable_list):
    do_something()
    return
def test():
    return random.random()

def decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

# 用法1:
f = decorator(test)

# 用法2:在 test 定义时加上 @
@decorator
def test():
    return random.random()

class Person:
    def __init__(self, name, age): # 构建函数
        # do_something

    @property # 将函数名作为属性,可按属性访问
    def name(self):
        return self._name

class Student(Person): # 继承
    pass # 占位

BeautifulSoup

import requests
from bs4 import BeautifulSoup

url = 'https://bj.lianjia.com/zufang/'
resp = requests.get(url)
soup = BeautifulSoup(resp.text, 'lxml')

link_divs = soup.find_all('div', class_="pic-panel") # 按类查 divs
links = [div.a.get('href') for div in link_divs] # 取 div 上 a 标签的 href 属性
# div_elem.text 是取 div 中的文本
# a_elem.get('href') 是取 a 中的属性

科学计算 numpy

import numpy as np

# 定义
a_list = list(range(10)) # 生成列表
b = np.array(a_list) # 从 list 中生成数组
c = np.zeros(10, dtype=int) # 生成 10 个元素值为 0 的数组,第二个参数可省略,默认 float 类型
d = np.zeros((4, 4)) # 二维四行四列的数组
e = np.ones((4, 4), dtype=float) # 值为 1
f = np.full((3, 3), 3.14) # 自己设定值
g = zeros_like(f) # 按 f 变量的结构生成值为 0 的数组。还有 ones_like(), full_like()
np.random.random() # 加强版的 random,可生成随机数为值的数组
np.arange(0, 10, 2) # 从 0 到 10 步长为 2 生成数组
np.linspace(0, 3, 10) # 从 0 到 3 生成 10 个元素的数组,线性取值
np.eye(5) # 生成 5 行 5 列的单位矩阵

# 取值
f[-1][0] # 数组取元素也可以用 -1 代表最后一个元素
f[2, 0] # 等同于 f[2][0]
f[:2, :2] # 多维数组也可以切片
f[:2][:1] # 这种方式就不等同于 f[:2, :1] 了,等同于 (f[:2])[:1]

# 属性
a.ndim # 维度
a.shape # shape,如 (3, 3) 3 * 3
a.size # 空间大小(元素个数)
a.dtype # 类型
a.itemsize # 元素占空间大小,如 8 字节
a.ntypes # 变量总共占空间大小

# 运算
a + 10 # 每个元素 +10,等价于 a.add(10)
# 还有其他操作符,特殊的: `//` 为 floor_divide

# 比较
a > 3 # 返回 True/False 的数组,比较每个元素
a != 3
a == a
np.all(a > -1) # 是否所有元素均大于 -1,返回一个 True/False
np.any(a > -1) # 是否包含任一元素大于 -1

# 变形
a.reshape(4, 5) # 元素数量要相等才能用
# 排序
np.sort(a)
a.sort()
a.sort(axis=0)
# 拼接
np.concatenate([], axis=0) # 拼接的数组放数组中,拼接的方向

数据计算 pandas

DataFrame

画图 matplotlib

import matplotlib.pyplot as plt
%matplotlib inline # 此行指明把图画在 xxx 处(示例用的是 notebook)
x = np.linspace(0, 10, 20) # 0 - 10 共 20 个数
y = np.sin(x) # 函数
plt.plot(x, y) # 画出图;plt.plot(x, y, '--') 用虚线画

fig = plt.figure() # 生成画幕
plt.plot(x, y)
fig.savefig('path/to/save')

(这个库比较复杂,并且对我现在也没多大用处,知道就行,不再细看整理了)

上一篇 下一篇

猜你喜欢

热点阅读