Python 有很多内置函数,灵活使用可以帮到大忙。本文目前收录:
slice()
set()
round()
map()
zip()
filter()
reduce()(非内置,属于 functools 库)
sorted()
值得注意的是: Python3 以后, map()、zip()、filter() 返回对象不再是 列表 ,而是 迭代器 。
迭代器 是 Python 中很重要的东西,有疑问的可以参见:
Python yield 使用浅析
Iterables vs. Iterators vs. Generators
切片
当我们需要截取 list 或者获取其逆序时,切片是一个不错的帮手。
>>>l = [0, 1, 2, 3]
>>>l[:]
[0, 1, 2, 3]
>>>l[2:]
[2, 3]
>>>l[:3]
[0, 1, 2]
>>>l[::-1]
[3, 2, 1, 0]
>>>l[-1:-2:-1]
[3]
语法即 r = l[i:j:s] 这里我们来解释下这几个参数含义:
字母
含义
描述
s
步长
缺省时为1
i
起始元素位置
当s>0,缺省时为0,当s<0,缺省时为-1
j
终止元素位置(不包含该元素,即[i, j))
当s>0,缺省时为len(r),当s<0,缺省时为-len(r)-1
与之对应的就是内置函数 slice()
>>>myslice=slice(0,2)
>>>myslice
slice(0, 2, None) # 分别对应 [i, j, s]
>>>l[myslice]
[0, 1]
集合运算
>>>before = [0, 1, 2]
>>>after = [1, 2, 3]
>>>print(list(set(before) & (set(after))))
[1, 2]
>>>list_union = list(set(before) | (set(after)))
>>>list_union
[0, 1, 2, 3]
>>>add_items = list(set(list_union) - (set(before)))
>>>add_items
[3]
>>>del_items = list(set(list_union) - (set(after)))
>>>del_items
[0]
由此我们得出了前后两个 list 详细差异。
set() 函数可以创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集(&)、差集(-)、并集(|)等。
浮点数精度控制
一般我们使用 round() 函数控制浮点数精度。
>>>round(1.1)
1
>>>round(1.12, 1)
1.1
>>>round(1.123, 2)
1.12
第一个参数是一个浮点数,第二个参数是保留的小数位数,可选,如果不写的话默认保留到整数。
如果对截取后的精确度有要求,参加以下链接:
数据过滤(filter)
使用 help(filter) 查看官方文档:
class filter(object) | filter(function or None, iterable) --> filter object | | Return an iterator yielding those items of iterable for which function(item) | is true. If function is None, return the items that are true.
例子:
>>>list(filter(lambda x: x > 2, [0, 1, 2, 3]))
[3]
>>>list(filter(None, [0, 1, 2]))
[1, 2]
map()
map() 可以批量处理数据,与filter() 相比,输入可以是多个可迭代对象
class map(object) | map(func, *iterables) --> map object | | Make an iterator that computes the function using arguments from | each of the iterables. Stops when the shortest iterable is exhausted.
例子:
>>>list(map(lambda x : x * 2, [1, 2, 3]))
[2, 4, 6]
# 多个迭代对象时,参数与迭代对象按顺序一一对应
# 当两个迭代对象不一样长时,以最短的为主
>>>list(map(lambda x : [x * 2, x + 1], [1, 2, 3]))
[[2, 2], [4, 3], [6, 4]]
>>>list(map(lambda x, y : [x - y, x + y], [1, 2, 3], [3, 2, 1, 0]))
[[-2, 4], [0, 4], [2, 4]]
>>>def add(x, y):
... return x + y
...
>>>list(map(add, [1, 2, 3], [3, 2, 1, 0]))
[4, 4, 4]
# 类型转换
>>>list(map(int, "1234"))
[1, 2, 3, 4]
以上只是一部分,灵活运用能有更大的用处。
打包解包(zip)
官方文档:
class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration.
可以将多个迭代对象同一索引下的 item 打包到一个元组中去。
例子:
>>>list(zip([1, 2, 3], [1, 2, 3]))
[(1, 1), (2, 2), (3, 3)]
>>>list(zip([1, 2, 3, 4], [1, 2, 3]))
[(1, 1), (2, 2), (3, 3)]
# 使用 * 可以解包
>>>list(zip(*[(1, 1), (2, 2), (3, 3)]))
[(1, 2, 3), (1, 2, 3)]
# 使用 zip 构造 map
>>>key = [1, 2, 3]
>>>value = ["a", "b", "c"]
>>>dict(zip(key, value))
{1: 'a', 2: 'b', 3: 'c'}
reduce()
处理可迭代对象的每一项,得出一个值,这个值可以是数值,也可以是列表等。
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
# 特别注意: function 有且仅有两个参数。 initial 为初始化值,如果有,第一次运算时,会用此值与
# sequence 中第一个值进行计算,如果没有,会用 sequence 的前两个值进行计算。计算出的值再与 sequence
# 后的值依次计算,最终得出结果。
例子:
# (((1 + 2) + 3) + 4)
>>>reduce(lambda x, y : x + y, [1, 2, 3, 4])
10
>>>reduce(lambda x, y : x + y, [2, 3, 4], 1)
10
>>>reduce(operator.add, [2, 3, 4], 1)
10
# sequence 为空时
>>>reduce(operator.add, [], 1)
1
# list 加法
>>>reduce(operator.add, [[1, 2]], [2, 3, 4])
[2, 3, 4, 1, 2]
lambda 表达式
为什么会有 lambda 表达式?或者说哪些场合适用于 lambda 表达式?
1、函数功能简单,只有几行,使用 lambda 表达式清晰明了;
2、函数只被调用很少次,专门写个函数,“污染命名空间”
上面我们已经用到 lambda 表达式,下面我们让它与 sorted 配合,实现各种高难度排序。
注意:dict 的 key 采用 hash 实现,本来就是无序的,但我们可以得到按照规则排序后其 key 值列表,按照列表顺序可到的排序后的 dict
先来看看 sorted() 函数:
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
例子:
# 对字符串的每个字母排序
>>>sorted("abc")
['a', 'b', 'c']
# 按字母排序
>>>sorted(["b", "c", "a"])
['a', 'b', 'c']
>>>sorted(["b", "c", "a"], reverse=True)
['c', 'b', 'a']
# dict 按 key 排序,输出 key 列表
>>>dic = {1:"b", 3:"a", 2:"c"}
>>>sorted(dic)
[1, 2, 3]
# dict 按 value 排序,输出 key 列表
>>>sorted(dic, key=lambda k : dic[k])
[3, 1, 2]
# list 嵌套 list
>>>lis = [[1, 2, 3], [1, 2, 4], [2, 1, 1]]
>>>sorted(lis)
[[1, 2, 3], [1, 2, 4], [2, 1, 1]]
# list 嵌套 dict
>>>lis = [{"name" : "张三", "score" : 10}, {"name": "李四", "score" : 8},
{"name": "王五", "score" : 11}]
>>>sorted(lis, key=lambda x : x["score"])
[{'name': '李四', 'score': 8}, {'name': '张三', 'score': 10}, {'name': '王五', 'score': 11}]