Python中常用的内置函数总结
一、map
map()
函数接收两个参数,一个是函数,一个是可迭代的对象(list、数组等),map将传入的函数依次作用到序列的每个元素,并把结果作为新的迭代器返回。
用法:
map(function,iterable)
下面的例子是将输入的list中的小写改为大写。
def makeupper(word):
return word.upper()
colors=['red','yellow','green','black']
colors_uppercase=list(map(makeupper,colors))
print(colors_uppercase)
二、enumerate
我们在遍历数组或者列表的时可能还需要统计迭代的次数,通过enumerate()
函数可以实现这个操作。
colors=['red','yellow','green','black']
for id,color in enumerate(colors):
print(id,color)
三、zip
zip()
函数是将多个列表按照元素顺序组织成单独的元组。其中列表的中元素的个数可以相同也可以不同
列表元素个数一致
colors=['red','yellow','green','black']
fruits=['apple','pineapple','grapes','cherry']
for item in zip(colors,fruits):
print(item)
列表元素个数不一致
colors=['red','yellow','green','black']
fruits=['apple','pineapple','grapes','cherry']
prices=[100,50,120]
for item in zip(colors,fruits,prices):
print(item)
四、filter
filter()
的作用是从列表或者元组中返回满足条件的元素,组成新的列表或者元组。
def checkupper(word):
return True if word.isupper else False
original_list=['APPLe','SAMSUNG','NoKiA','OPPO','Vivo','MicroMax']
filtered_list=list(filter(checkupper,original_list))
print("Original list is: {}".format(original_list))
print("Filtered list is: {}".format(filtered_list))
五、lambda
lambda()
是用来实现python中的匿名函数或者实现比较简单的函数。使用lambda可以简化的书写形式,使代码更为简洁
add2=lambda x:x+2
print(add2(2))
a=[10,2,5,3,1,9]
b=[(lambda x:x%3==0)(i) for i in a ]
print(b)
#和filter一起使用
b=filter(lambda x:x%3==0,a)
print(list(b))