程序小屋

记录生活中的点滴,分享、学习、创新

文章内容 1623753400

python笔记

列表

允许负索引。

增加元素

# 元素末尾添加, 修改原数组

list.append('element')

 

# 元素任意位置添加, 修改原数组

list.insert(0,'element')

删除元素

# del语句删除指定位置元素

del list[2]

 

# pop方法删除列表指定位置元素并返回之。若不指定,删除列表末尾元素。

list.pop()

 

 

# 根据值删除元素。删除列表第一个值为'elment'的元素

list.remove('element')

排序

# 永久性排序. 修改原数组

list.sort()  # 正序

list.sort(reverse=True) # 倒序

 

 

# 临时排序. 不修改原数组

sorted(list)

sorted(list,reverse=True)

 

# 反转列表

list.reverse()

 

数值列表创建

# 起始位置,终止位置(不包含),步长

range(1,11,2)   # [1, 3, 5, 7, 9]

列表解析

list = [value**2 for value in range(1,11)]

 

# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表切片

# 切片位置用冒号分割,不指定位置则到尽头

list[1:5]  

函数

python中函数形参定义顺序:位置实参/关键字实参(正常定义的形参)、带默认值的形参、接收任意数量的形参

函数指定关键字实参和默认值形参时,等号两边不要有空格。函数命名尽量只使用小写字母和下划线

下面是任意数量位置形参,用 * 表示,接收任意数量的值组成的元组

def build_profile(first_name, last_name, *user_info):

    profile = {}

    profile['first_name'] = first_name

    profile['last_name'] = last_name

    for key, value in enumerate(user_info):

        profile['other_'+str(key)] = value

    return profile

 

 

profile = build_profile('luo', 'ion', 23, 'Guangzhou')

print(profile)

# {'first_name': 'luo', 'last_name': 'ion', 'other_0': 23, 'other_1': 'Guangzhou'}

下面是任意数量关键字形参,用 ** 表示,接收任意数量的键值对组成的字典

# **是任意数量关键字形参,接收任意数量的键值对

def build_profile(first_name, last_name, **user_info):

    profile = {}

    profile['first_name'] = first_name

    profile['last_name'] = last_name

    for key, value in user_info.items():

        profile[key] = value

    return profile

 

 

profile = build_profile('luo', 'ion', age=23, address='Guangzhou')

print(profile)

# {'first_name': 'luo', 'last_name': 'ion', 'age': 23, 'address': 'Guangzhou'}

函数导入

# 导入整个模块

import module_name

# 使用模块的某个函数

module_name.function_name()

 

 

# 导入模块中特定的函数

from module_name import function_name0, function_name1, function_name2

# 使用

function_name0()

 

 

# 用as给函数和模块指定别名

from module_name import function_name as fn

# 使用 fn()

import module_name as mn

# 使用 mn.function_name()

 

 

# 导入模块中的所有函数,需要谨慎,防止函数或者变量命名相同导致的意想不到的结果

from module_name import *

函数式编程:贴近计算(底层语言贴近计算机)

函数 != 函数式

函数式编程的特点:

把计算视为函数而非指令

纯函数式编程:不需要变量,没有副作用,测试简单

支持高阶函数,代码简洁

python支持的函数式编程特点:

不是纯函数式编程:允许有变量

支持高阶函数:函数也可以作为变量传入

支持闭包:有了闭包就能返回函数

有限度地支持匿名函数

 

高阶函数:能接收函数做参数的函数

pythion中,变量可以指向函数,函数的参数可以接收变量,所以一个函数可以接收另外一个函数作为参数

>>> def add(x,y,f):

...     return f(x)+f(y)

...

>>> add(-5,9,abs)

14

 

math模块常见函数

函数  说明  实例

 math.e  自然常数e  >>> math.e

2.718281828459045

 math.pi  圆周率pi  >>> math.pi

3.141592653589793

 math.degrees(x)  弧度转度  >>> math.degrees(math.pi)

180.0

 math.radians(x)  度转弧度  >>> math.radians(45)

0.7853981633974483

 math.exp(x)  返回e的x次方  >>> math.exp(2)

7.38905609893065

 math.expm1(x)  返回e的x次方减1  >>> math.expm1(2)

6.38905609893065

 math.log(x[, base])  返回x的以base为底的对数,base默认为e  >>> math.log(math.e)

1.0

>>> math.log(2, 10)

0.30102999566398114

 math.log10(x)  返回x的以10为底的对数  >>> math.log10(2)

0.30102999566398114

 math.log1p(x)  返回1+x的自然对数(以e为底)  >>> math.log1p(math.e-1)

1.0

 math.pow(x, y)  返回x的y次方  >>> math.pow(5,3)

125.0

 math.sqrt(x)  返回x的平方根  >>> math.sqrt(3)

1.7320508075688772

 math.ceil(x)  返回不小于x的整数  >>> math.ceil(5.2)

6.0

 math.floor(x)  返回不大于x的整数  >>> math.floor(5.8)

5.0

 math.trunc(x)  返回x的整数部分  >>> math.trunc(5.8)

5

 math.modf(x)  返回x的小数和整数  >>> math.modf(5.2)

(0.20000000000000018, 5.0)

 math.fabs(x)  返回x的绝对值  >>> math.fabs(-5)

5.0

 math.fmod(x, y)  返回x%y(取余)  >>> math.fmod(5,2)

1.0

 math.fsum([x, y, ...])  返回无损精度的和  >>> 0.1+0.2+0.3

0.6000000000000001

>>> math.fsum([0.1, 0.2, 0.3])

0.6

 math.factorial(x)  返回x的阶乘  >>> math.factorial(5)

120

 math.isinf(x)  若x为无穷大,返回True;否则,返回False  >>> math.isinf(1.0e+308)

False

>>> math.isinf(1.0e+309)

True

 math.isnan(x)  若x不是数字,返回True;否则,返回False  >>> math.isnan(1.2e3)

False

 math.hypot(x, y)  返回以x和y为直角边的斜边长  >>> math.hypot(3,4)

5.0

 math.copysign(x, y)  若y<0,返回-1乘以x的绝对值;

 否则,返回x的绝对值  >>> math.copysign(5.2, -1)

-5.2

 math.frexp(x)  返回m和i,满足m乘以2的i次方  >>> math.frexp(3)

(0.75, 2)

 math.ldexp(m, i)  返回m乘以2的i次方  >>> math.ldexp(0.75, 2)

3.0

 math.sin(x)  返回x(弧度)的三角正弦值  >>> math.sin(math.radians(30))

0.49999999999999994

 math.asin(x)  返回x的反三角正弦值  >>> math.asin(0.5)

0.5235987755982989

 math.cos(x)  返回x(弧度)的三角余弦值  >>> math.cos(math.radians(45))

0.7071067811865476

 math.acos(x)  返回x的反三角余弦值  >>> math.acos(math.sqrt(2)/2)

0.7853981633974483

 math.tan(x)  返回x(弧度)的三角正切值  >>> math.tan(math.radians(60))

1.7320508075688767

 math.atan(x)  返回x的反三角正切值  >>> math.atan(1.7320508075688767)

1.0471975511965976

 math.atan2(x, y)  返回x/y的反三角正切值  >>> math.atan2(2,1)

1.1071487177940904

 

python中map()函数

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

def f(x):

    return x*x

 

def format_name(s):

    return s.lower().title()

 

print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

# [1, 4, 9, 16, 25, 36, 49, 64, 81]

 

print map(format_name, ['adam', 'LISA', 'barT'])

# ['Adam', 'Lisa', 'Bart']

注意:

map()函数不改变原有的 list,而是返回一个新的 list。

由于list包含的元素可以是任何类型,因此,map() 不仅仅可以处理只包含数值的 list,事实上它可以处理包含任意类型的 list,只要传入的函数f可以处理这种数据类型。

python中reduce()函数

reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。reduce()还可以接收第3个可选参数,作为计算的初始值。

# 求和函数reduce实现

def f(x, y):

    return x + y

 

print reduce(f, [1, 3, 5], 100)

# 109

 

# Python内置了求和函数sum(),但没有求积的函数,请利用recude()来求积:

def prod(x, y):

    return x*y

 

print reduce(prod, [2, 4, 5, 7, 12])

# 3360

python中filter()函数

filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

# 请利用filter()过滤出1~100中平方根是整数的数:

import math

 

def is_sqr(x):

    r = math.sqrt(x)

    return r % 1 == 0

 

print filter(is_sqr, range(1, 101))

# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

利用filter(),可以完成很多有用的功能,例如,删除 None 或者空字符串:

def is_not_empty(

*