【Python】Function

1
2
3
def <函数名> (<参数列表>):
<函数体>
return <返回值列表>
  • 形参不需要声明类型,也不需要指定函数返回值类型

  • 允许嵌套定义函数

全局变量用global进行引用(否则默认新建局部变量)

1
2
3
4
5
6
7
8
def func():
global a
a = 2
b = 1

a = 1
b = 2
print(a, b) #a = 2, b = 2

但如果是列表,会改动外部全局的列表

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

def func():
l.append(6)
print(l) #[1,2,6]

print(l) #[1,2,6]
print(*l) #1 2 6

可以用默认的参数

1
2
3
def func(a, b=2):
...
# 不给b传参时默认b=2

形参带*表示任意数量的参数作为元组传入,带**表示任意数量的参数作为字典传入(一般放在最后一个参数位置)

内置函数

id

id(a):返回对象唯一标识符

1
2
3
>>> a = 2
>>> id(a)
140260960941824

type

type(a):返回变量类型

1
2
3
>>> a = 2
>>> type(a)
<type 'int'>

dir

dir(a):返回变量(数据类型、class等)可以调用的方法

1
2
3
4
5
>>> a = 2
>>> dir(a)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

del

del(a):删除变量

1
2
3
4
5
6
7
8
>>> a = 2
>>> a
2
>>> del(a)
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

sorted

sorted(iterable[, key[, reverse]])

iterable:序列,如字符串、列表、元组等

key:用来进行比较的元素

reverse:排序规则,True降序,False升序(默认)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
## 元组
>>> a = (3,5,4)
>>> sorted(a)
[3, 4, 5]
>>> a #不变
(3, 5, 4)

## 字典
>>> d = {'a':90, 'c':100, 'b':80}
>>> sorted(d)
['a', 'b', 'c']
>>> sorted(d.values())
[80, 90, 100]
>>> sorted(d.items())
[('a', 90), ('b', 80), ('c', 100)]
>>> sorted(d.items(), key = lambda x : x[1])
[('b', 80), ('a', 90), ('c', 100)]

lambda 匿名函数

1
2
3
>>> f = lambda x : x*x
>>> f(5)
25

map

根据提供的函数对指定序列做映射

map(function, iterable, …)

function:以参数序列中的每一个元素调用function函数

iterable:序列,返回包含每次function函数返回值的新列表或迭代器

1
2
>>> a = list(map(lambda x : x*x, [1,2,3,4]))
[1,4,9,16]

zip

将可迭代的对象作为参数,将对象中对应的元素打包成元组,然后返回由元组组成的列表或迭代器。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同

zip([iterable, …])

iterable:一个或多个序列

返回值:返回元组列表

1
2
3
4
5
6
>>> a = [1,2,3]
>>> b = [5,6,7,8]
>>> list(zip(a,b))
[(1,5), (2,6), (3,7)]
>>> dict(zip(a,b))
{1:5, 2:6, 3:7}

eval

执行字符串表达式,并返回表达式的值

eval(expression[, globals[, locals]])

1
2
3
4
>>> x = 6
>>> y = 3
>>> eval('x+3*y')
15

exec

与eval类似,执行动态语句,不同的是其主要用于执行语句块

exec(object[, globals[, locals]])

all

判断给定的可迭代参数

all(iterable)

如果iterable中所有元素都为true则返回true,否则返回false

元素除了0、空、None、False外全算True

空列表、空元组返回值为True

any

any(iterable)

有一个为True则返回True,全为False则返回False