Python中常用的内置函数总结

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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GHZhao_GIS_RS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值