Python3函数(一)

1.返回值

 当函数返回值为多个时,可以用多个变量来接收,或自动组装为元组

def fun(a,b):
    a,b=11,12
    return a,b
print(fun(1,2))

2.三个大数据常用的函数

 1>map(func, *iterables)

自动遍历序列各元素后,执行单个元素的对应操作后返回结果   

foo=[2,18,9,22,17,24,8,12,27]
foo2=[1,2,3]
map1=map(lambda x:x*2+10,foo)
def tt(x):
    return x*2+10
map2=map(tt,foo)

 PS:在Python中,function也是对象,所以可以不写(),如果写()为方法或函数的调用

   2>filter(function or None, iterable) 

单个元素中,过滤出满足条件的元素

f=filter(lambda x:x>10,foo)
print(f)
for i in f:
    print(i,end=" ")

   3>reduce()

将序列里所有元素进行统计后,返回一个结果

#Python3中需要导入reduce
from functools import reduce
def re(x,y):
    return x+y
r=reduce(lambda a,b:a*b,foo)
# r=reduce(re,foo)
print("r={0}".format(r))
PS:由于reduce()是两个元素执行操作,所以参数里的方法需要两个参数

3.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可以提供自定义key函数以自定义排序顺序。
    reverse flag can be set to request the result in descending order.可以设置反向标志以按降序返回结果。

扫描二维码关注公众号,回复: 1463649 查看本文章
L = [('d',2),('a',4),('b',3),('c',2)]

#倒序先按数字排序,后按字母,
print(sorted(L,key=lambda x:(x[1],x[0]),reverse=True))

#将[0,1]中的0索引和1索引颠倒
a=lambda x:(x[1],x[0])
print(a([0,1]))


猜你喜欢

转载自blog.csdn.net/awangbsi/article/details/80513709