0%

Python学习笔记01

资料:廖雪峰Python教程

IDE:Spyder

数据类型

  1. \(\stackrel{\mathrm{list}}{\text{列表}}\)

    1
    2
    L = ['Apple', 123, True]  # 元素数据类型不同
    s = ['python', 'java', ['asp', 'php'], 'scheme'] # list嵌套list

    list中元素可变

  2. \(\stackrel{\mathrm{tuple}}{\text{元组}}\)

    1
    2
    3
    t = ()  # 空tuple
    t = (1,) # 只有1个元素的tuple
    t = ('a', 'b', ['A', 'B']) # tuple嵌套list

    tuple中元素不可变

  3. \(\stackrel{\mathrm{dict}}{\text{字典}}\)

    1
    d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}  # 键-值(key-value)对应
  4. \(\stackrel{\mathrm{set}}{\text{集合}}\)

    1
    2
    s1 = set([1, 1, 2, 2, 3, 3])  # 由list创建set
    s2 = {1, 1, 2, 2, 3, 3} # set只有key, 没有value

    set中元素无序

函数的参数

函数的参数包括:必选参数、默认参数、可变参数、关键字参数等

以 默认参数 + 可变参数 为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def product(x1=None, *x2):  # x1为默认参数, x2为可变参数
if x1 is None:
# if not x1:
raise TypeError('请输入参数')
else:
y = x1
for t in x2:
y *= t
return y

if product(5) != 5:
print('测试失败!')
elif product(5, 6) != 30:
print('测试失败!')
elif product(5, 6, 7) != 210:
print('测试失败!')
elif product(5, 6, 7, 9) != 1890:
print('测试失败!')
else:
try:
product()
print('测试失败!')
except TypeError:
print('测试成功!')

切片

Slice

原则:左闭右开

1
2
3
4
5
6
7
8
9
10
L = list(range(100))  # 第0个 -> 第99个, [0, 1, 2, 3, ..., 99], 100个数

L[:5] # 前5个数, 第0个 -> 第4个, [0, 1, 2, 3, 4]
L[-5:] # 后5个数, 第95个 -> 第99个, [95, 96, 97, 98, 99]

L[5:10] # 第5个 -> 第9个, [5, 6, 7, 8, 9]
L[-5:-1] # 第95个 -> 第98个, [95, 96, 97, 98]

L[:10:2] # 前10个数, 每两个取一个, [0, 2, 4, 6, 8]
L[::5] # 所有数, 每5个取一个

抽象迭代

  1. Python的for循环抽象程度要高于C的for循环

    1
    2
    3
    4
    5
    6
    7
    d = {'a': 1, 'b': 2, 'c': 3}
    for key in d:
    print(key)
    for value in d.values():
    print(value)
    for k, v in d.items():
    print(k, '=', v)
  2. 通过collections模块的Iterable类型判断能否迭代

    1
    2
    3
    4
    from collections import Iterable
    isinstance('abc', Iterable) # str可迭代, True
    isinstance([1,2,3], Iterable) # list可迭代, True
    isinstance(123, Iterable) # 整数不可迭代, False
  3. Python内置的enumerate函数可以把一个list变成索引-元素对

    1
    2
    for i, value in enumerate(['A', 'B', 'C']):
    print(i, value)
  4. 同时引用两个变量

    1
    2
    for x, y in [(1, 1), (2, 4), (3, 9)]:
    print(x, y)

列表生成式

List Comprehensions

  1. 基本用法

    1
    list(range(1, 11))  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. 循环赋值

    1
    2
    3
    L = []
    for x in range(1, 11):
    L.append(x * x) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  3. 循环简记

    1
    [x * x for x in range(1, 11)]  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  4. 循环嵌套

    1
    [m + n for m in 'ABC' for n in 'XYZ']  # 全排列
  5. 循环 + 判断

    1
    [x for x in range(1, 5) if x % 2 == 0]  # [2, 4]

    for后面的if是过滤条件,不能有else

  6. 判断 + 循环

    1
    [x if x % 2 == 0 else -x for x in range(1, 5)]  # [-1, 2, -3, 4]

    for前面的if ... else是表达式,必须有else

高阶函数

\(\stackrel{\mathrm{higher-order}}{\text{高阶}}~\stackrel{\mathrm{function}}{\text{函数}}\):一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

map/reduce
  1. map 一般抽象

    1
    2
    3
    4
    5
    def f(x):
    return x * x

    list(map(f, [1, 2, 3, 4, 5])) # 抽象f, [1, 4, 9, 16, 25]
    list(map(str, [1, 2, 3, 4, 5])) # 抽象str, ['1', '2', '3', '4', '5']

    MATLAB里的arrayfun.运算与map的功能类似

  2. reduce 企业级抽象

    把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

    1
    reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)  # 四个元素的伪代码

    例如,将序列[6, 3, 2, 4]变换成整数6324

    1
    2
    3
    4
    5
    6
    7
    from functools import reduce

    def fn(x, y):
    return x * 10 + y

    reduce(fn, [6, 3, 2, 4])
    reduce(fn, [2, 7, 1, 8, 2, 8, 1, 8, 2, 8, 4, 5, 9, 0, 4]) # 再多点
filter

filter把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

例如,删掉偶数,只保留奇数:

1
2
3
4
def is_odd(n):
return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # [1, 5, 9, 15]
sorted
  1. Python内置的sorted函数就可以对list进行排序

    1
    sorted([36, 5, -12, 9, -21])  # [-21, -12, 5, 9, 36]
  2. 接收一个key函数来实现自定义排序

    1
    sorted([36, 5, -12, 9, -21], key=abs)  # [5, 9, -12, -21, 36]

匿名函数

格式

1
2
f = lambda x, y: x * x + y
f(5, 5) # 30

匿名函数只能有一个表达式

MATLAB中的匿名函数:f=@(x,y) x^2+y

等价于

1
2
def f(x):
return x * x + y

偏函数

\(\stackrel{\mathrm{partial}}{\text{偏}}~\stackrel{\mathrm{function}}{\text{函数}}\):是通过设定参数的默认值,可以降低函数调用的难度。

int()函数提供额外的base参数(默认值为10),如果传入base参数,就可以做N进制的转换:

1
2
int('6324', base=8)  # 3284为10进制结果
int('6324', base=16) # 25380为16进制结果

可以定义一个int8()的函数,默认把base=8传进去:

1
2
def int8(x, base=8):
return int(x, base)

利用functools.partial创建一个偏函数:

1
2
3
4
import functools

int8 = functools.partial(int, base=8)
int8('6324')