几个好用的python内建函数
目录
在python开发中,经常能看到许多人在重复写一些简单的小函数或lambda表达式,而这些功能早已在python中内置了……
map
对 iterables 中的每个元素逐个进行处理。
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.
示例1:
将[0, 10)的数乘以2:
#!/usr/bin/python3 number = map(lambda x: 2*x, range(10)) print(list(number))
输出结果:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
示例2:
将[0, 10)与[100, 120)的数逐项相乘:
#!/usr/bin/python3 multi = map(lambda x, y: x*y, range(10), range(100, 120)) print(list(multi))
输出结果:
# 只取了[100, 120)的前10项 [0, 101, 204, 309, 416, 525, 636, 749, 864, 981]
注意:
- python3中map是一个内建类(builtin class map),返回值是一个map对象(map object)
- python2中map是一个内建函数(builtin function),返回值是一个列表(list)
filter
过滤 iterable 中为 true 的元素。
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.
示例:
获取[0, 20)的奇数:
#!/usr/bin/python3 odd = filter(lambda x: x % 2 == 1, range(20)) print(list(odd))
输出结果:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
注意:
- python3中filter是一个内建类(builtin class filter),返回值是一个filter对象(filter object)
- python2中filter是一个内建函数(builtin function),返回值是一个list,tuple或者string
sorted
对 iterable 的元素进行排序(默认升序)。
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.
可以使用key参数来指定排序的规则。
示例:
进行一个简单的排序:
#!/usr/bin/python3 a = [1, 4, 5, 2, 10, 3] print(sorted(a)) # 输出:[1, 2, 3, 4, 5, 10]
对tuple进行排序:
#!/usr/bin/python3 a = (("a", 2), ("b", 1), ("c", 4), ("d", 3)) print(sorted(a, key=lambda x: x[1]) # 输出:[('b', 1), ('a', 2), ('d', 3), ('c', 4)]
对dict进行排序:
#!/usr/bin/python3 import operator a = {"a": 2, "b": 1, "c": 4, "d": 3} print(sorted(a.items(), key=operator.itemgetter(1))) # 输出:[('b', 1), ('a', 2), ('d', 3), ('c', 4)]
zip
对多个iterable进行合并,按最短元素进行截断。
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.
示例:
将[0..9]、[20..29]、[40..49]合并为一个列表:
#!/usr/bin/python3 a, b, c = range(0, 10), range(20, 30), range(40, 50) for v in zip(a, b, c): print(v)
输出:
(0, 20, 40) (1, 21, 41) (2, 22, 42) (3, 23, 43) (4, 24, 44) (5, 25, 45) (6, 26, 46) (7, 27, 47) (8, 28, 48) (9, 29, 49)
注意:
- python3中zip是一个内建类(builtin class zip),返回值是一个zip对象(zip object)
- python2中zip是一个内建函数(builtin function),返回值是一个list
all
如果iterable为空或全部元素都为True,则返回True。
all(iterable, /) Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.
示例:
#!/usr/bin/python3 # True all([1, 2, 3, "a", "b"]) # False all([1, 2, 3, "a", ""])
any
如果iterable中有至少一个元素为True,则返回True。
any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
示例:
#!/usr/bin/python3 # True any([0, 1, "a"]) # False any([0, False, ""])
enumerate
对一个iterable同时返回下标(index)和值(value),可以指定下标的起点。
enumerate(iterable[, start]) -> iterator for index, value of iterable | | Return an enumerate object. iterable must be another object that supports | iteration. The enumerate object yields pairs containing a count (from | start, which defaults to zero) and a value yielded by the iterable argument. | enumerate is useful for obtaining an indexed list: | (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
示例:
#!/usr/bin/python3 a = ["a", "b", "c", "d"] for idx, val in enumerate(a, 5): print(idx, val)
输出:
5 a 6 b 7 c 8 d
注意:
- python2和python3中enumerate均为内建类(builtin class enumerate)
码字很辛苦,转载请注明来自ChenJiehua的《几个好用的python内建函数》
2018-07-07 2018-07-07 python
评论