Python中的常用方法/经典函数(持续更新)

该篇博文主要记录常见/经典的Python函数(持续更新
———————————————2020.06.10————————————————

匿名函数lambda

最常用的一个函数,与常规函数不同它是一个表达式。
格式:lambda arg1,arg2,.....argn:expression
':'之前是参数,':'之后的表达式就是lambda的返回结果,不需要return

c = lambda x, y=2: x + y
print(c(10))
>> 12

map函数

map(function, Iterate) — 对可迭代对象Iterate的每一个元素执行function操作

l = [1,2,3,4,5]
ll = map(lambda x :x*2, l)
print(list(ll))
>> [2, 4, 6, 8, 10]

字典get()函数

l = ['apple','red','1','apple','1','red','2','apple']

dict1 = dict()
for i in l:
    dict1[i] = dict1.get(i, 0) + 1
    
print(dict1)

>>{'apple': 3, 'red': 2, '1': 2, '2': 1}

可能用途:统计list中的元素出现的个数

Counter 方法

l = ['apple','red','1','apple','1','red','2','apple']

from collections import Counter
print(Counter(l))

可能用途:统计list中的元素出现的个数

filter方法

filter(function,Iterate) — 过滤出满足条件的元素对象

strr = 'I am a Chinese, My name is :hhh'
ll = list(filter(lambda x : x.isalnum(),strr.lower()))
print(ll)
>> ['i', 'a', 'm', 'a', 'c', 'h', 'i', 'n', 'e', 's', 'e', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'h', 'h', 'h']

可能用途:过滤出可迭代对象中满足条件的元素

np.where(condition, x, y)

满足条件,输出x,否则输出y。功能与filter类似

import numpy as np
ll = np.array([1,2,3,4,5])
print(np.where(ll>3,ll,0))

>> [0 0 0 4 5]

np.where(condition)

输出满足条件的元素对应坐标

import numpy as np
l = np.array([3,4,9,12,1,5,6])
np.where(l % 3 == 0)

>>(array([0, 2, 3, 6], dtype=int64),)

可能用途:寻找array中的满足条件元素下标

and / or

and中含0,返回0; 均为非0时,返回后一个值

求解 1+2+3+…+n

class Solution:
    def sumNums(self, n: int) -> int:
        return n!=0 and n+self.sumNums(n-1)

or 中返回非0的第一个元素

print(1 or 3)
print(0 or 2)
print(5 or 9)
>>1
>>2
>>5

append / extend / ‘+’

append是往列表后添加一整个对象,这个对象可以是列表,也可以是元素
extend是只接受一个列表作为参数,并将该参数的每个元素都添加到原有的列表中
‘+’ 的作用于extend类似

a = ['cen','lian']
b = ['haha','kik','hkh']
a.append(b)
print(a)
>>['cen', 'lian', ['haha', 'kik', 'hkh']]
a = ['cen','lian']
b = ['haha','kik','hkh']
a.extend(b)
print(a)
>>['cen', 'lian', 'haha', 'kik', 'hkh']
a = ['cen','lian']
b = ['haha','kik','hkh']
a = a + b
print(a)
>>['cen', 'lian', 'haha', 'kik', 'hkh']
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值