python 内置函数

可通过help(xxx)来查看x x x函数的相关信息,如下图
help()
如果有__iter__()说明该内建函数可以迭代器。

  1. 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.

>>> a= [1,2,3,4,5,6,7]
>>> list(filter(lambda x:x>2,a))
[3, 4, 5, 6, 7]
  1. 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.

>>> a = [1,2,3]
>>> map(lambda x:x,a)
<map object at 0x10d218828>
>>> list(map(lambda x:x,a))
[1, 2, 3]
>>> list(map(lambda x:x+1,a))
[2, 3, 4]
>>> b= [4,5,6]
>>> list(map(lambda x,y:x+y,a,b))
[5, 7, 9]
  1. 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.

# 导入才可使用reduce
>>> from functools import reduce 
# sum = ((1+2)+3)+4
>>> reduce(lambda x,y:x+y,[2,3,4],1)
10
  1. 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.

4.1 将元组转置


>>> zip((1,2,3),(4,5,6))
<zip object at 0x10734d208>
>>> list(zip((1,2,3),(4,5,6)))
[(1, 4), (2, 5), (3, 6)]
>>> for i in zip((1,2,3),(4,5,6)):
...     print(i)
... 
(1, 4)
(2, 5)
(3, 6)
>>> 

4.2 对调dict 的value和key

>>> dict1={'a':'aaa','b':'bb'}
>>> zip(dict1.values(),dict1.keys())
<zip object at 0x10734d508>
>>> dict2=zip(dict1.values(),dict1.keys())
>>> print(dict(dict2))
{'aaa': 'a', 'bb': 'b'}
>>> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值