python基础总结

1Python的数据类型

答:数字(number)、字符串(string)、列表(list)、元组(tuple)、字典(dict)、集合(set

Number/string/tuple不可更改,list/dict/set可以

 

2、列表和元组的区别

答:列表可变类型,元组不可变

3、字符串中查找字符索引位置

1) 查找第一次出现的字符

s.index(c), 找不到raise ValueError

s.find(c), 找不到返回-1

2)查找最后一次出现的字符

s.rindex(c), 找不到raise ValueError

s.rfind(c), 找不到返回-1

3)查找所有出现的字符,找不到返回空列表。

[m.start() for m in re.finditer('z', s)]

4)找指定start,end出现的字符

s.index(c,start=None, end=None)

4、获取对象的内存地址

id(s)

5==is的区别

==是比较值相等,is是比较内存地址相等

 

6、匿名函数

a = lambda x, y: x + y
print(a(3, 6))

7、map函数

map(func,*iterables)

可迭代对象的元素依次被func处理,组成map对象,返回迭代器,

def tes(t):
    return t*2
lis1 = [10, 5, 8]
print(list(map(tes, lis1)))
print(lis1*2)

[20, 10, 16]

[10, 5, 8, 10, 5, 8]

# 也可传入多个对象

lis2 = [3, 6, 1]
print(list(map(lambda a, b: a + b, lis1, lis2)))
返回:[13, 11, 9]

8、zip函数

zip(*iterables)

可迭代对象的元素对应打包成一个个元组,元组组成zip对象,返回迭代器

print(list(zip('abcdefg', range(3), range(4))))

[('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]

 

9、浅拷贝和深拷贝的区别

针对可变类型,深拷贝不会变更,浅拷贝在子对象变更时会变更,因为id一样。

 

10、两个列表如何组成字典

print(dict(zip(['n', 'a', 'x'], ['zm', 18, 'm'])))

{'n': 'zm', 'a': 18, 'x': 'm'}

 

11、列表推导式或者生成式

print([i for i in range(10) if i % 2 == 0])

[0, 2, 4, 6, 8]

 

12、函数的参数类型

1)必需参数,必须传入且顺序正确;

2)关键字参数,指定用参数名来传参,不需要指定顺序;

3)默认参数,不传参就使用默认值;

4)不定长参数,*args表示参数会以元组的形式导入,**kwargs表示参数会以字典的形式导入。

1))必需参数

调用函数时必须传入的参数,传参数与形参数一致,函数定义时只定义参数名

2))以参数名参数值作为键值对来传入,

4))不定长参数*

举例:*把传入的多个位置参数打包成元组,赋值给形参args

def test1(*args):
    print(args)
test1(1,3,6,9,0)

res:(1,3,6,9,0)

举例: 

def test1(a,b,*args):
    print(a,b)
    print(args)
test1(1,3,*[6,9,0])

res:1,3  \n(6,9,0)

举例:*拆分

print(*[1,2,3])
print(1,2,3)

res:1 2 3 \n 1 2 3

举例:

def test1(a,b,c,d,e):
    print(a,b)
    print(c,d,e)
test1(1,3,*[6,9,0])

res:1,3  \n6,9,0

4))不定长参数**

举例:**把传入的多个关键字参数打包成字典,赋值给形参kwargs

def test1(a,b,**kwargs):
    print(a,b)
    print(kwargs)
test1(1,3,c=6,d=9,e=0)

res:1,3  \n{'c':6,'d':9,'e':0}

举例:**拆分

def test1(a,b,c,d,e):
    print(a,b)
    print(c,d,e)
test1(1,3,**{'c':6,'d':9,'e':0})

res:1,3  \n6,9,0

 

13、__new____init__的区别

同时有__new____init__的时候:

1) new是在实例创建前被调用,用于创建实例,返回该实例对象,是静态方法;

Init是实例对象创建完成后被调用,用于初始化类实例,是实例方法。

2) new必有参数cls(即当前类),必有返回实例;

3) new返回的实例传给initselfinit不需要有返回值;

4) new不返回,init不会被调用。

class Tes():
    def __new__(cls, *args, **kwargs):
        print('new__')
        return super(Tes, cls).__new__(cls)

    def __init__(self):
        print('init__')


Tes()

new__

init__

 

14、super()

super(cls, self).__init__()

cls--当前类, self当前类实例,

cls.mro()

super()是返回当前类在实例的mro列表中的下一个类。

 

https://blog.csdn.net/weixin_40734030/article/details/122863308

 

15、生成器迭代器装饰器

生成器:一个返回迭代器的函数,使用yield。遇到yield会暂停并保存信息,返回yield的值,并在下一次next()方法时从当前位置继续执行。

Eg:生成斐波那契数列

def fin(n):
    a, b=0, 1
    for i in range(n):
        yield a
        a,b = b, a+b

f = fin(10)
while True:
    try:
        print(next(f), end=" ")
    except StopIteration:
        sys.exit()

0 1 1 2 3 5 8 13 21 34

 

迭代器:可以记住遍历位置,从第一个元素开始访问,只能往前不能后退。

t1=iter(iterable),t1就是迭代器,可迭代对象list/string/tuple

next(t1)去读取元素。

 

装饰器:改变函数的功能和性质,

@staticmethod

 

16、python的自省/反射

获取对象的类型、属性。

type()id()isinstance()issubclass()

17、常用模块

1、Random

random.random()

[0,1)之间的一个随机浮点数

random.randint(2, 8)

指定范围间的一个整数

random.randrange(2, 8, 2)

range(start, stop, step) 返回一个随机元素

random.choice(seq)

seq返回一个元素

random.choices(string.ascii_letters + '*&#%&@()', k=5)

seq返回k个元素组成的列表

random.sample(string.ascii_letters, 5)

同上

2、Time

time.time()

当前时间戳

time.sleep(5)

time.localtime()

P_tuple本地时间

time.strftime('%Y-%m-%d %H:%M:%S', p_tuple)

P_tuple----》格式化时间

time.strptime('2011-10-12 8:10:33', '%Y-%m-%d %H:%M:%S')

时间----P_tuple

time.mktime(p_tuple)

P_tuple-----》时间戳

time.gmtime(sec)    UTC时区

时间戳-----P_tuple

 

3、Threading

import threading
def test1():
    for i in range(10):
        print(random.choice(string.ascii_lowercase))
def test2():
    for i in range(10):
        print(random.choice(string.digits))
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
t1.join()
t2.join()

4、Os

os.getcwd()

当前工作路径

os.path.join(path)

拼接路径

os.path.isfile(path)

判断path是否为文件

os.path.exists(path)

Path存在返回True

os.listdir(path)

返回Path路径下所有目录名和文件名,列表形式

os.rename('te1.py', 'te1temp.py')

重命名文件或目录

5、Re

match:从起始位置匹配,返回对象,失败返回None

search:全部字符串匹配第一个,返回对象,失败返回None

findall:全部字符串匹配所有,返回列表,失败返回空列表

res = re.search(r'(\d+)[a-z]+(\d+)', 'eer45t903ket')
print(res.group())
print(res.group(0))
print(res.group(1))
print(res.group(2))
print(res.groups())

45t903

45t903

45

903

('45', '903')

 

sub:替换

split

Flag---re.I 忽略大小写

正则模式:

^-----开头, $-----末尾   .-----任意字符

[0-9]===\d

[^0-9] ===\D

\w------数字字母下划线

\s-------任意空白字符\n\t\r\f

[a-z]  [A-Z]  [a-zA-Z0-9]

a|b ---- ab

*------0到无数次   +-----1到无数次   ?01

 

6、Selenium

Driver放置路径:Python38-32\Scripts

chrom_options = webdriver.ChromeOptions()

# 最大化运行

chrom_options.add_argument(--start-maximized)

# 跳过“您的连接不是私密连接”

options.add_argument("--ignore-certificate-errors")

brower = webdeiver.Chrom(options=chrom_options)

brower,get(https:xxx)

查找元素:id(唯一性)、xpathnamelinkclass

获取文本(text,发送文本(send_keys(xxx))、点击元素(click())、清除(clear())、

鼠标悬停(move_to_element(ele))、是否enable(is_enabled())、是否被选中(is_selected()

 

三种等待方式:强制等待sleep(10)/隐式等待:无条件等待10s

1) 显式等待:有条件等待10s

Import WebDriverWait

Import expected_conditions as EC

WebDriverWait(driver, 10,0.5).until(EC.visibity_of_element_located(ele))

 

浏览器弹出框

alart = driver.switch_to_alart()

alart.text

alart.accpet()

alart.dismiss()

 

下拉框

Import Select

sel = Selest(ele)

sel.select_by_index(0)

Sel.select_by_value(zz)

 

文件上传

<input type=file.....元素找到,send_keys(‘’)

 

 

 

 

 

 

18、两个列表取重复、除重复的元素

&----重复点

|----合并

^-----合并-重复点

t1 = [3, 5, 2, 1]
t2 = [8, 5, 3, 7, 6]
print(set(t1) - set(t2))
print(set(t2) - set(t1))
print(set(t1) ^ set(t2))
print(set(t1) & set(t2))
print(set(t1) | set(t2))

{1, 2}

{8, 6, 7}

{1, 2, 6, 7, 8}

{3, 5}

{1, 2, 3, 5, 6, 7, 8}

 

19、列表字符串首字母大写其他小写

l1 = ['erE08gT', 'erUUher', 'RhrJe']
print(list(map(lambda x: x[0].upper() + x[1:].lower(), l1)))
print(list(map(lambda x: str(x).capitalize(), l1)))

['Ere08gt', 'Eruuher', 'Rhrje']

 20、__name__

__name__是内置属性,每一个py文件都有属于自己的__name__。

当前py文件默认该值为"__main__",if __name__ == "__main__":作为主函数入口。

 

如果该py文件被其它py文件调用,那在其它文件中该文件的值为"文件名"

 运行

 

20、租车骑绿道

部门组织绿道骑行团建活动。租用公共双人自行车骑行,每辆自行车最多坐两人,最大载重M

给出部门每个人的体重,请问最多需要租用多少双人自行车。

输入描述:

第一行两个数字mn,自行车限重m,代表部门总人数n

第二行,n个数字,代表每个人的体重。体重都小于等于自行车限重m

0<m<=200

0<n<=1000000

输出描述:

最小需要的双人自行车数量。

示例1

输入

3 4

3 2 2 1

输出

3

m, n = map(int, input().split())
wei = list(map(int, input().split()))
wei.sort()
cnt = 0
l = 0
r = n - 1
while l <= r:
    if wei[l] + wei[r] <= m:
        cnt += 1
        l += 1
        r -= 1
    else:
        cnt += 1
        r -= 1
print(cnt)

 

21、通信误码

信号传播过程中会出现一些误码,不同的数字表示不同的误码ID,取值范围为1~65535,用一个数组记录误码出现的情况。每个误码出现的次数代表误码频度,请找出记录中包含频度最高误码的最小子数组长度。

输入描述:

误码总数目:取值范围为0~255,取值为0表示没有误码的情况。

误码出现频率数组:误码ID范围为1~65535,数组长度为1~1000

输出描述:

包含频率最高的误码最小子数组长度。

示例1

输入:

5

1 2 2 4 1

输出:

2

说明:

频度最高的有12,他们的频度均为2.

可能的记录数组为[2,2][1,2,2,4,1]

最短的长度为2

示例2

输入

7

1 2 2 4 2 1 1

输出

4

说明

最短的为[2,2,4,2]

 

n = int(input())
ma = list(map(int, input().split()))
ma_dic = {}
for index, x in enumerate(ma):
    if x not in ma_dic:
        ma_dic[x] = [index]
    else:
        ma_dic[x] = ma_dic[x]+[index]
res = []
max_cnt = max(map(len, ma_dic.values()))
for k, v in ma_dic.items():
    if max_cnt == len(v):
        res.append(v[-1]-v[0]+1)
print(min(res))

22、最少数量线段覆盖

给定坐标轴上的一组线段,线段的起点和终点均为整数并且长度不小于1,请你从中找到最少数量的线段,这些线段可以覆盖住所有线段。

输入描述:

第一行输入为所有线段的数量,不超过10000,后面每行表示一条线段,格式为“xy,xy分别表示起点和终点,取值范围是[-10^5,10^5]

输出描述:

最少线段数量,为正整数。

示例1

输入:

3

1,4

2,5

3,6

输出:

2

说明:

选取2条线段[1,4][3,6]即可,这两条线段可以覆盖[2,5]

n = int(input())
a = [list(map(int, input().split(','))) for x in range(n)]
a.sort(key=lambda x: (x[0], -x[1]))
cnt = 0
r = a[0][0] - 1
mx = r
p = 0
while p < n:
    if a[p][0] <= r:
        mx = max(a[p][1], mx)
        p += 1
    else:
        if mx > r:
            cnt += 1
            r = mx
        else:
            cnt += 1
            r = a[p][1]
            p += 1
if mx > r:
    cnt += 1
print(cnt)

posted @ 2023-06-19 09:54  zmm521  阅读(47)  评论(0)    收藏  举报