美文网首页
map/filter/reduce等内置函数的用法

map/filter/reduce等内置函数的用法

作者: 小码码 | 来源:发表于2018-07-06 17:10 被阅读72次

1 map函数

  • 用法一:用lambda表达式
list1=[1,2,3,4,5,6]
result = map(lambda x:x+1,list1)
print(result)       # <map object at 0x0000000000B6D518> 
print(list(result))   # [2, 3, 4, 5, 6, 7]
备注:直接打印result,返回的是map结果的地址,需要转换成list类型才能正常显示出来。

含义:依次取出list1中的元素,传递给lambda中的x,处理以后的结果放在一个新的列表中返回。

  • 用法二:传递函数名
def add(x):
    return x+1

list1=[1,2,3,4,5,6]
result = map(add,list1)
print(result)
print(list(result))       

2 filter函数

names = ['lili_sb','a_sb','lulu','ixi_sb','lala']

def sb_show(name):
    return name.endswith('sb')

#用法一:传入函数名
res=filter(sb_show,names)  
#用法二:用lambda
res=filter(lambda name:name.endswith('sb'), names)

print(res)   #<filter object at 0x0000000001108898>
print(list(res))   #['lili_sb', 'a_sb', 'ixi_sb']

含义:依次取出names中的元素,进行条件判断,将满足条件的元素放入一个新的列表中返回

  • 应用示例
people = [
    {'name':'lili','age':18},
    {'name':'lucy','age':25},
    {'name':'lala','age':15}
]

res = list(filter(lambda p:p['age']<=18, people))
print(res)       # [{'age': 18, 'name': 'lili'}, {'age': 15, 'name': 'lala'}]

3 reduce函数

  • 内部实现过程:将一个列表中的元素依次取出做运算,返回一个结果
nums = [1,2,3,4,100]
def reduce_test(func,array,init=None):
    if init is None:
        res = array.pop[0]
    else:
         res = init
    for num in array:
        res = func(res,num)
    return res

result = reduce_test(lambda x,y:x*y,nums,init=1)
print(result)   #2400

示例说明:将列表nums中的元素做乘积运算。若指定初始值init,就用初始值,没有指定的话就用第一个元素。

  • reduce的使用
from functools import reduce

nums = [1,2,3,4,100]
result = reduce(lambda x,y:x*y, nums,1)   #nums为列表,1为初始值
print(result)     #    2400
print(reduce(lambda x,y:x+y,range(100),100))       #5050
print(reduce(lambda x,y:x+y,range(1,101)))    #5050

4 eval函数

eval 的功能:(1)提取字符串中的对象 (2)表达式运算

# 提取字符串中的对象 
dict_str = "{'name':'alex'}"
print(eval(dict_str))         #{'name': 'alex'}

#表达式运算
express = '1+2*5*(3-1)-10'
print(eval(express))       #11

5 hash函数

功能:将数据转成hash值
注意点:
(1)可hash的数据是不可变数据,可变数据不能hash;
(2)同一数据的hash值相同;无论什么数据,对应hash值的长度相同且固定

print(hash('name'))                         #-2263070152599717894
print(hash('ghjhjkkkljljljlllllllll'))         #-8325204691958646476
print(hash('name'))                         #-2263070152599717894

6 isinstance函数

功能:判断数据类型

print(isinstance('abc',str))          #True
print(isinstance([],list))               #True
print(isinstance([],set))              #False

7 zip函数

  • 功能:zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同
  • 应用示例
a=[1,2,3]
b=[4,5,6]

zipped4=zip(a)
print(list(zipped4))                    #[(1,), (2,), (3,)]

zipped = zip(a,b)
print(zipped)                              #<zip object at 0x0000000000A3C888>
print(list(zipped))                       #[(1, 4), (2, 5), (3, 6)]

c=[7,8,9,10,11]
zipped2=zip(b,c)
print(list(zipped2))                     #[(4, 7), (5, 8), (6, 9)]   长度与最短的对象相同
zipped3=zip(a,b,c)
print(list(zipped3))                     #[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

print(list(zip('hello','123456')))     #[('h', '1'), ('e', '2'), ('l', '3'), ('l', '4'), ('o', '5')]
print(list(zip(['a','b'],'123456')))    #[('a', '1'), ('b', '2')]
  • zip函数总结:
    (1)参数可以是1个或多个可迭代对象
    (2)作为参数的可迭代对象可以是列表、元祖、字符串

  • min/max/zip混合使用

age_dic={'age1':18,'age3':100,'age4':20,'age2':30}
print(max(age_dic.values()))    #100
print(max(age_dic))                 #age4  默认按key来比较
print(max(zip(age_dic.values(),age_dic.keys())))     #(100, 'age3')

people = [
    {'name':'alex','age':1000},
    {'name':'lili','age':10000},
    {'name':'lucy','age':9000},
    {'name':'mimi','age':18},
]
#取出people中age最大的人的信息
print(max(people))    #报错 TypeError: unorderable types: dict() > dict()
max_people=max(people,key=lambda dic:dic['age'])
print(max_people)      #{'age': 10000, 'name': 'lili'}

8 pow()幂函数

print(pow(3,3))      #27  3**3
print(pow(3,3,2))    #1   3**3%2

9 reversed()函数

l=[1,2,3,4]
print(list(reversed(l)))      #[4, 3, 2, 1]   反序排列

10 sorted函数

people = [
    {'name':'alex','age':1000},
    {'name':'lili','age':10000},
    {'name':'lucy','age':9000},
    {'name':'mimi','age':18},
]
print(sorted(people,key=lambda dic:dic['age']))    #[{'name': 'mimi', 'age': 18}, {'name': 'alex', 'age': 1000}, {'name': 'lucy', 'age': 9000}, {'name': 'lili', 'age': 10000}]

name_dic={
    'caya':900,
    'lili':200,
     'xixi':300
}
print(sorted(name_dic))                        #['caya', 'lili', 'xixi']   默认按key来排序的
print(sorted(name_dic,key=lambda key:name_dic[key]))        #['lili', 'xixi', 'caya']  按value来排序

11 import函数

__import__('test')   #导入test模块  同import test

module_name = 'test'
m=__import__(module_name )
m.say_hi()

12 其他的内置函数

# 获取绝对值
def abs(*args, **kwargs): # real signature unknown
    """ Return the absolute value of the argument. """
    pass

print(abs(-10))    #10

 #判断元素是不是都为真
def all(*args, **kwargs): # real signature unknown
    """
    Return True if bool(x) is True for all values x in the iterable.
    
    If the iterable is empty, return True.
    """
    pass

print(all(['aa','']))     #False    有一个为空则为False

#判断是不是有真元素
def any(*args, **kwargs): # real signature unknown
    """
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.
    """
    pass

print(any(['aa','']))      #True

#转为ascii码,中文不能转成ascii码
def ascii(*args, **kwargs): # real signature unknown
    """
    Return an ASCII-only representation of an object.
    
    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \\x, \\u or \\U escapes. This generates a string similar
    to that returned by repr() in Python 2.
    """
    pass


bool(1)   判断元素是否为真
bytes()   转为二进制
chr()    将数字转为ASCII字符
dict()   转为字典
dir()   文件目录
divmod(5/2)   除法运算   (2,1)   2余1
str()   对象转成字符串
bin()  转为二进制
hex()  转为十六进制
oct()   转为八进制
max()  最大值
min()   最小值
sum()  求和
type()  获取类型

相关文章

网友评论

      本文标题:map/filter/reduce等内置函数的用法

      本文链接:https://www.haomeiwen.com/subject/chtbuftx.html