Python各种奇妙的API

一、sortedlist

演示代码

from sortedcontainers import SortedList

test_sl.add(2) #添加元素
test_sl.add(8)
test_sl.add(1)
print(test_sl)
 
test_sl.remove(4) #删除元素 元素不存在时会报错
test_sl.discard(1) #删除元素 元素不存在时不会报错
print(test_sl)
 
test_sl.pop() #移除最后一个元素
print(test_sl)
 
pos_left = test_sl.bisect_left(2) #查找元素存在的位置
pos_right = test_sl.bisect_left(2)
print(pos_left, pos_right)
 
num = test_sl.count(2) #计数
print(num)
 
ind = test_sl.index(2) #返回第一次出现的下标
print(ind)
 
output:
SortedList([1, 2, 3, 4, 5, 6, 7])
SortedList([1, 1, 2, 2, 3, 4, 5, 6, 7, 8])
SortedList([1, 2, 2, 3, 5, 6, 7, 8])
SortedList([1, 2, 2, 3, 5, 6, 7])
1 1
2
1

  作为强大的python,当然可以自定义lambda表达式比较函数啦

from sortedcontainers import SortedList
from operator import neg
 
test_sl = SortedList([3,5,1,2,7,6,4], key=neg)
 
print(test_sl)
 
output:
SortedKeyList([7, 6, 5, 4, 3, 2, 1], key=<built-in function neg>)

from sortedcontainers import SortedList
 
test_str = SortedList(["1", "431", "34"], key=lambda item:len(item))
print(test_str)
 
output:
SortedKeyList(['1', '34', '431'], key=<function <lambda> at 0x7fb883b36820>)

二、*args和**kwargs

1. *args——可选的位置参数

  假如需要写一个求和函数。

def my_sum(a,b):
	return a+b
print(my_sum(a,b))

  那么如果需要传入三个参数是不是需要这样呢。

def my_sum(a,b,c):
	return a+b+c
print(my_sum(a,b,c))

  答案是不需要。我们只要借助神奇的*args即可。

def my_sum(*args):
	return sum(args)
#对于该函数,我们不管传多少个参数都是可以的
print(my_sum(a,b))

2. **kwargs

  既然已经有了可选的位置参数(args),还要可选的关键词参数(kwargs)干嘛呢?关键词参数相当于给参数一个关键词,有着特定的用途,关键词对这个特殊用途进行标识。由于需要关键词,因此kwargs的传入函数的类型是字典。
  假如我想定义一个求和函数,在需要的时候对求和进行除法运算。这时就需要用到关键词参数。

def my_weird_sum(*args,**kwargs):
	dominator=kwargs.get("dominator",1)#如果没有该键值,则返回1
	return (sum(args)/dominator)
print(my_weird_sum(a,b,c))
print(my_weird_sum(a,b,c,dominator=3))

二、collections库

  Counter 是 dict 字典的子类,Counter 拥有类似字典的 key 键和 value 值,只不过 Counter 中的键为待计数的元素,而 value 值为对应元素出现的次数 count。由于 Counter 类继承自 dict 类,所以 Counter 类可以使用 dict 类的方法。下面分别从 Counter 所特有的方法和一些字典的常规方法来介绍。

  • elements()方法
      elements()方法返回一个迭代器,可以通过list或其他方法将其中的元素输出,输出的结果为对应出现次数的元素。
test=Counter({'a':1,'b':0,'c':-1})
print(list(test))
#['a']
  • most_common()
      most_common([n]),返回一个出现次数从大到小的前 n 个元素的列表。(不输入参数默认返回所有)
  • subtract()
      将两个Counter中元素对应计数相减

Counter支持集合运算

>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                           # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d                           # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d                           # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d                           # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})

三、zip()函数

  zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符对tuple实参进行解包。具体关于*操作符可以看这篇博客
  其中最神奇的操作要属对zip()矩阵转置的实现。

x=[[1,2,3],
  [3,4,5],
  [5,6,7]]
x=list(map(list,zip(*x[::-1])))#[::-1]表示倒序复制一遍

ps:

map()函数
map(function,iter),是对可迭代对象全部使用function
例如:map(str,list(a))

  其他精彩操作可以参考这篇博客

四、filter()函数

  filter(function,iter),用于过滤可迭代对象。

e,g.1 正则与filter()结合的题目

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        words=re.split('[^\w]',paragraph)  #用非数字,字母分隔
        words=list(filter(None,words))  #去除匹配到的空格
        counts=defaultdict(int)
        for w in words:
            w=w.lower()
            if w not in banned:
                counts[w]+=1
        res=max(counts,key=counts.get)  #counts.get按每个元素的键值寻找最大
        return res
#不过这题好像可以更简单。。。
class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        cnt=Counter(re.findall(r'\w+',paragraph.lower())).most_common()
        for (w,_) in cnt:
            if w not in banned:return w
posted @ 2022-05-25 22:02  Wasser007  阅读(68)  评论(0编辑  收藏  举报