reduce函数
功能:
- 对一个序列进行压缩运算,得到一个value。
- python2中,reduce() 是内置函数,而现在,py3中,它被移植到functools 模块中。
- from functools import reduce
格式:
- reduce(function,iterable,[initial])
- function 必须要传入两个参数
- iterable —> 列表/元组
from functools import reduce
y = [2, 3, 4, 5, 6]
z = reduce(lambda x, y: x + y, y)# 若初始值为100,即z = reduce(lambda x, y: x + y, y,100)
print(z)
#20 #则结果为120
apply函数
功能:
- pandas 中,应用对象是pandas中的DataFrame或者Series
- 直接对DataFrame或者Series应用函数
- 对pandas中groupby之后的聚合对象应用apply
zip函数
功能:
- 将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,返回由这些元组构成的对象。
- 程度不一样的时候,以长度短的为准
注意:
利用*操作符,与zip相反,进行解压。
格式:
zip(iterable1,iterable2,…)
- iterable —> 两个或多个可迭代序列(字符串,列表,元组,字典)
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
ziptest1 = zip(a, b)
print(list(ziptest1))
#[(1, 4), (2, 5), (3, 6)]
for i in ziptest1:
print(i, end=' ')
#(1, 4) (2, 5) (3, 6)
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
ziptest1 = zip(a, b)
Star_zip = zip(*ziptest1)
print(list(Star_zip))
#[(1, 2, 3), (4, 5, 6)]
a = {1: 11, 2: 22}
b = {3: 33, 4: 44}
c = {5: 55, 6: 66}
tp = tuple(c)
print(tp)
print(list(zip(a, b, c)))
#(5, 6)
#[(1, 3, 5), (2, 4, 6)]
用filter判断回文数:
def is_palindrome(n):
palind = int(str(n)[::-1])
if palind == n:
return palind
print(list(filter(is_palindrome, range(1, 1000))))
print(list(filter(lambda x: str(x) == str(x)[::-1], range(1, 1000))))
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]
#结果同