python Counter() 函数
Counter() 是 collections 库中的一个函数,可以用来统计一个 python 列表、字符串、元组等可迭代对象中每个元素出现的次数,并返回一个字典
1、以统计列表中的词频
from collections import Counter
nums = [1, 1, 1, 6, 6, 6, 7, 8]
count = Counter(nums) # 统计词频
for k, v in count.items():
print(k, v)
print(count)
"""
输出:
1 3
6 3
7 1
8 1
Counter({1: 3, 6: 3, 7: 1, 8: 1})
"""
使用 Counter 统计完词频后可以使用 most_common 方法来查找出现频率最高的 k 个数字及其出现次数。
知识点:long long 是C++的64位整型的基本类型
sort函数
大多数排序操作是针对列表的,所以需要先将字符串转换成列表,进行排序,然后再合并成字符串。
s="abxc"
l1=list(s) #['a', 'b', 'x', 'c']
l1.sort() #['a', 'b', 'c', 'x']
s1="".join(l1) #'abcx'
1.运用list的sort()函数。sort()函数对原列表进行排序,没有返回值
另外,缺省为升序排序,通过reverse = True参数实现降序排列
l1=[1,6,2]
l1.sort(reverse = True) #[6,2,1]
2..运用sorted() 函数。sorted() 函数对列表等可迭代的对象进行排序操作。返回一个新的list,而不是在原来的基础上进行的操作,不同于list.sort(),必须使用返回值。也可以进行降序排列
l1=[1,6,2]
l2=sorted(l1) #[1, 2, 6],升序(缺省模式),必须使用返回值,l1本身不变。
l2=sorted(l1,reverse = True) #[6, 2, 1],降序
enumerate函数
Enumerate()函数—python
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
Python3二分查找库函数bisect(), bisect_left()和bisect_right()介绍
前提:列表有序!!!
bisect()和bisect_right()等同,那下面就介绍bisect_left()和bisec_right()的区别!
index1 = bisect(ls, x) #第1个参数是列表,第2个参数是要查找的数,返回值为索引
bisect_right返回大于x的第一个下标,也就是小于等于x的个数
bisect_left返回大于等于x的第一个下标,也就是小于x的个数。
注意事项
1.如果列表中没有元素x,那么bisect_left(ls, x)和bisec_right(ls, x)返回相同的值,该值是x在ls中“合适的插入点索引,使得数组有序”
import bisect
ls = [1,5,9,13,17]
index1 = bisect.bisect(ls,7)
index2 = bisect.bisect_left(ls,7)
index3 = bisect.bisect_right(ls,7)
print("index1 = {}, index2 = {}, index3 = {}".format(index1, index2, index3))
结果
index1 = 2, index2 = 2, index3 = 2
2.如果列表中只有一个元素等于x,那么bisect_left(ls, x)的值是x在ls中的索引,ls[index2] = x。而bisec_right(ls, x)的值是x在ls中的索引加1
import bisect
ls = [1,5,9,13,17]
index1 = bisect.bisect(ls,9)
index2 = bisect.bisect_left(ls,9)
index3 = bisect.bisect_right(ls,9)
print("index1 = {}, index2 = {}, index3 = {}".format(index1, index2, index3))
结果:index1 = 3, index2 = 2, index3 = 3
3.如果列表中存在多个元素等于x,那么bisect_left(ls, x)返回最左边的那个索引,此时ls[index2] = x。bisect_right(ls, x)返回最右边的那个索引加1
bisect.bisect_left(a, x, lo=0, hi=len(a))
返回在序列 a
中将 x
插入的位置(将 x
插入后,仍保持升序排列)。如果序列中存在等于 x
的元素,则返回该元素的左侧位置。可选参数 lo
和 hi
分别指定查找的左右边界,默认值分别为 0 和序列长度。
bisect.bisect_right(a, x, lo=0, hi=len(a))
返回在序列 a
中将 x
插入的位置(将 x
插入后,仍保持升序排列)。如果序列中存在等于 x
的元素,则返回该元素的右侧位置。可选参数 lo
和 hi
分别指定查找的左右边界,默认值分别为 0 和序列长度
并且,左闭右开
python基础--除法,取整,取模(取余)
# val_caculate.py
a = 10 # a是整数
print('10/3 = ',10/3)
print('9/3 = ',9/3)
print('10//3 = ',10//3)
print('10%3 = ',10%3)
print('15//4 = ',15//4)
说明:
除法:/;
取整://;
取余:%
特别注意:对于//,是向下取整,即不会进行四舍五入。所以15//4 = 3的结果是3而不是4
10/3 = 3.3333333333333335
9/3 = 3.0
10//3 = 3
10%3 = 1
15//4 = 3
all函数
all()
函数的作用是检查可迭代对象中所有的元素是否都为真(即每个元素在布尔上下文中都为True)。如果所有元素都为真,则all()
返回True;否则,返回False。
# 示例1:所有元素都为真
print(all([1, 2, 3, 4])) # 输出:True
print(all(('a', 'b', 'c'))) # 输出:True
print(all({1, 2, 3})) # 输出:True
# 示例2:存在元素为假
print(all([1, 2, 0, 4])) # 输出:False,因为0被视为False
print(all(('a', 'b', ''))) # 输出:False,因为空字符串被视为False
print(all({1, 2, None})) # 输出:False,因为None被视为False
# 示例3:空的可迭代对象
print(all([])) # 输出:True,空列表被视为True
print(all(())) # 输出:True,空元组被视为True
print(all({})) # 输出:True,空集合被视为True
在编程题中的体现
if len(s)>ans and all(j==i or not in_subseq(s,t) for j,t in enumerate(strs)):
这里的意思就是在遍历strs时,都要满足j==1或者not in_subseq=1,才能算True
set函数
定义:set是一种集合数据类型,表示一个无序且不重复的集合。set()方法可以用于创建一个空的集合,也可以将其他可迭代对象转换为集合。与其他Python数据类型不同,set没有索引,不能通过索引访问其元素,但可以使用一些方法来操作和访问集合中的元素。
常用方法
1.add()
语法:set.add(elmnt)
# 案例如下:
set1 = {1,2,3}
set1.add(4)
print(set1)
# 输出结果如下
{1, 2, 3, 4}
2.clear()
# clear()语法如下:
set.clear()
# 案例如下:
set1 = {1, 2, 3}
set1.clear()
print(set1)
# 输出结果如下:
set()
3.copy()【只是拷贝一个副本,不会影响原来的集合】
# 语法如下:
new_set = old_set.copy()
# 案列如下:
set1 = {1, 2, 3}
set2 = set1.copy()
set2.add(4)
print(set1)
print(set2)
# 输出结果如下:
{1, 2, 3}
{1, 2, 3, 4}
# 首先,我们创建了一个原始集合,然后使用copy方法创建了一个新集合,并在新集合中添加了一个元素4,
# 最后,我们打印了原始集合和复制出的新集合,可以看到两个集合互不影响。
4.差集difference()方法用于返回集合的差集,即返回的集合元素包含在第一个集合中,但不包含在第二个集合(方法的参数)中
# 语法如下:
set1.difference(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.difference(set2))
# 输出结果如下:
{1}
5.difference_update() :方法用于移除两个集合中都存在的元素
# 语法如下:
set1.difference_update(set2)
# 案例如下:
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 4}
set1.difference_update(set2)
print(set1)
# 输出结果如下
{1, 5}
6.discard() 方法语法:discard() 方法用于移除指定的集合元素。
该方法不同于 remove() 方法,因为 remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。
# 语法如下:
set.discard(value)
# 案例如下
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.discard(2), set2.discard(3)
print(set1, set2)
# 输出结果如下:
{1, 3} {2, 4}
# 删除不存在元素,不会引发任何异常
set1.discard(4)
print(set1)
# 输出结果如下
{1, 2, 3}
7.intersection() 方法用于返回两个或更多集合中都包含的元素,即交集
# 语法如下:
set1.intersection(set2, set3, ...)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1.intersection(set2)
print(set3)
# 输出结果如下:
{2, 3}
8.intersection_update()方法用于获取两个或更多集合中都重叠的元素,即计算交集。
intersection_update() 方法不同于 intersection() 方法,因为 intersection() 方法是返回一个新的集合,而 intersection_update() 方法是在原始的集合上移除不重叠的元素。
# 语法如下:
set1.intersection_update(set2, set3, ...)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.intersection_update(set2)
print(set1)
# 输出结果如下:
{2, 3}
9.isdisjoint() 方法用于判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
# 语法如下:
set1.isdisjoint(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {4, 5, 6}
print(set1.isdisjoint(set2))
print(set3.isdisjoint(set1))
# 输出如果如下:
False
True
10.issubset() 方法用于判断一个集合是否是另一个集合的子集。如果一个集合的所有元素都包含在另一个集合中,如果是则返回 True,否则返回 False
# 语法如下:
set1.issubset(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {1, 2, 3, 4}
print(set1.issubset(set2))
print(set1.issubset(set3))
# 输出结果如下:
False
True
11.pop() 方法用于随机移除一个元素并返回该元素的值。
# 语法如下:
set.pop()
# 案例如下:
# 随机移除一个元素:
set1 = {1, 2, 3, 4}
set1.pop()
print(set1)
# 结果如下:
{2, 3, 4}
# 输出返回值:
set1 = {1, 2, 3, 4}
print(set1.pop())
# 结果如下:
1
13.remove() 方法用于移除集合中的指定元素。
该方法不同于 discard() 方法,因为 remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。
# 语法如下:
set1.symmetric_difference(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.symmetric_difference(set2))
# 输出结果如下:
{1, 4}
14.symmetric_difference() 方法返回两个集合中不重复的元素集合,即会移除两个集合中都存在的元素,即返回两个集合中互不相同的元素集合。
# 语法如下:
set.remove(item)
# 案例如下:
set1 = {1, 2, 3, 4}
set1.remove(4)
print(set1)
# 输出结果如下:
{1, 2, 3}
16.union() 方法返回两个集合的并集,即包含了所有集合的元素,重复的元素只会出现一次。
# 语法如下:
set1.union(set2)
# 案例如下:
# 合并两个集合,重复元素只会出现一次:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.union(set2))
# 输出结果如下:
{1, 2, 3, 4}
# 合并多个集合:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5, 6, 7}
print(set1.union(set2, set3))
# 输出结果如下:
{1, 2, 3, 4, 5, 6, 7}
17.update() :方法用于修改当前集合,可以添加新的元素或集合到当前集合中,如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略。
# 语法如下:
set1.update(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.update(set2)
print(set1)
# 结果如下:
{1, 2, 3, 4}
18.当我们要随即从集合选择一个数作为函数的参数,可以用set(集合/列表。。。。)来实现
isdigit()方法
Python isdigit() 方法检测字符串是否只由数字组成,只对 0 和 正数有效。
语法:str.isdigit()
返回值
如果字符串只包含数字则返回 True 否则返回 False。
示例:
str = "123456" # 字符串只包含数字
print (str.isdigit())
str = "this is string example....wow!!!"
print (str.isdigit())
str = "0"
print (str.isdigit())
str = "-1"
print (str.isdigit())
#运行结果
True
False
True
False
split()方法
Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
语法:
str.split(str="", num=string.count(str)).
参数
- str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
- num -- 分割次数。默认为 -1, 即分隔所有。
示例:
print str.split( ); # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
#输出:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
txt = "Google#Runoob#Taobao#Facebook"
# 第二个参数为 1,返回两个参数列表
x = txt.split("#", 1)
#输出:['Google', 'Runoob#Taobao#Facebook']
format格式化函数
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
#结果:
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
数字格式化
>>> print("{:.2f}".format(3.1415926))
3.14
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:-.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:>10d} 13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d} 13 中间对齐 (宽度为10)
join函数
#对序列进行操作(分别使用' '与':'作为分隔符)
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido
#对字符串进行操作
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
#对元组进行操作
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
#对字典进行操作
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello
os.path.join()用于合并目录
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'
list(range)使用方法
range()
函数有三种形式:
-
range(stop)
:生成一个从0到stop-1
的整数序列。 -
range(start, stop)
:生成一个从start
到stop-1
的整数序列。 -
range(start, stop, step)
:生成一个从start
到stop-1
的整数序列,步长为step
。
numbers = list(range(5))
print(numbers) # 输出:[0, 1, 2, 3, 4]
numbers = list(range(2, 8))
print(numbers) # 输出:[2, 3, 4, 5, 6, 7]
numbers = list(range(1, 10, 2))
print(numbers) # 输出:[1, 3, 5, 7, 9]
zip和pairwise妙用
for (a1, b1), (a2, b2) in pairwise(zip(temperatureA, temperatureB)):
可以从A,B列表中每次都选出两个数进行组合
deque用法:
deque 是Python标准库 collections 中的一个类,实现了两端都可以操作的队列,相当于双端队列,与Python的基本数据类型列表很相似。
1. 单个数据入队
# coding=utf-8
import collections
queue = collections.deque()
queue.append('a')
queue.append('b')
queue.append('c')
print(queue)
queue.appendleft('A')
queue.appendleft('B')
print(queue)
结果:
deque(['a', 'b', 'c'])
deque(['B', 'A', 'a', 'b', 'c'])
append(item),添加一个数据到队列的尾部。与列表的append()方法功能相似。
appendleft(item),添加一个数据到队列的头部。与append()的添加方向相反。
2.指定位置插入数据
queue.insert(3, 'T')
print(queue)
结果:
deque(['d', 'c', 'B', 'T', 'A', 'a', 'b', 'c', 'D', 'E'])
3.出栈
deque 类中实现了队列两端的出队方法。
print(queue.pop())
print(queue.popleft())
print(queue)
结果:
E
d
deque(['c', 'B', 'T', 'A', 'a', 'b', 'c', 'D'])
pop(),将队列尾部的数据弹出,并作为返回值。
popleft(),将队列头部的数据弹出,并作为返回值。
4.deque返回指定值的数量和索引
print(queue.count('b'))
queue.append('b')
print(queue.count('b'))
print(queue.count('z'))
print(queue.index('T'))
结果:
1
2
0
2
5.deque的翻转和轮转
print(queue)
queue.reverse()
print(queue)
queue.rotate(3)
print(queue)
结果:
deque(['c', 'B', 'T', 'A', 'a', 'b', 'c', 'D', 'b'])
deque(['b', 'D', 'c', 'b', 'a', 'A', 'T', 'B', 'c'])
deque(['T', 'B', 'c', 'b', 'D', 'c', 'b', 'a', 'A'])
rotate(num),对队列中的数据进行轮转。每次轮转是将队尾的数据出队然后从队头入队,相当于先pop()再appendleft(item),retate(num)中传入轮转的次数。
6.删除
print(queue)
queue.remove('T')
print(queue)
queue.clear()
print(queue)
结果:
deque(['T', 'B', 'c', 'b', 'D', 'c', 'b', 'a', 'A'])
deque(['B', 'c', 'b', 'D', 'c', 'b', 'a', 'A'])
deque([])
数组去重
有一个不太会引起时间限制的求法
from collections import Counter
nums=[0,1,1,2,2,3,3,3,3]
nums.sort()
cnt = Counter(nums)
n = len(cnt)
nums = list(cnt.keys())
print(nums)
结果
[0, 1, 2, 3]