日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

Python基础高级用法,必须要掌握的知识点

發(fā)布時(shí)間:2025/3/20 python 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python基础高级用法,必须要掌握的知识点 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1.ChainMap

當(dāng)我們有2個(gè)字段o1和o2 你想將它們從合并后進(jìn)行查找操作(比如先從o1找,如果o1找不到,再去o2找),如下:

from collections import ChainMapo1 = {"a": 1, "c": 10} o2 = {"b": 5, "c": 4} o3 = ChainMap(o1, o2) print(o3) # ChainMap({'a': 1, 'c': 10}, {'b': 5, 'c': 4})print(o3["a"]) print(o3["b"]) print(o3["c"]) # 如果查尋一個(gè)不存在的key通過(guò)[]會(huì)報(bào)錯(cuò),我們可以通過(guò)get方式更緩和一點(diǎn) print(o3.get("d")) # None

當(dāng)然o3也具備字典的特性,我們通過(guò)刪除,更新,添加操作總是優(yōu)先影響第一個(gè)字典

# 更新 o3["c"] = 100 print(o3)# ChainMap({'a': 1, 'c': 100}, {'b': 5, 'c': 4}) print(o1) # {'a': 1, 'c': 100} # 刪除 del o3["c"] print(o3)# ChainMap({'a': 1}, {'b': 5, 'c': 4}) # 新增 o3["d"] = 20 print(o3)# ChainMap({'a': 1, 'd': 20}, {'b': 5, 'c': 4})

作為范圍變量用法

''' 學(xué)習(xí)中遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' values = ChainMap() values["x"] = 1 # 新建一個(gè)空的映射對(duì)象 values = values.new_child() values["x"] = 2 values = values.new_child() values["x"] = 3print(values) # ChainMap({'x': 3}, {'x': 2}, {'x': 1}) print(values["x"]) # 3# 類(lèi)似列表中取 [1:]切片 values = values.parents print(values)# ChainMap({'x': 2}, {'x': 1}) print(values["x"])# 2 values = values.parents print(values["x"]) # 1

2.字符串開(kāi)口結(jié)尾匹配

一般我們匹配字符串以開(kāi)頭或結(jié)尾用的方法是:startswith,endswith.
匹配是否存在

lst = ["hello.py", "world.py", "think.py"] lst2 = ["jsp.jar", "hello.vue", "foo.c"] print(any(name.endswith(".py") for name in lst2)) # False print(any(name.endswith(".py") for name in lst2)) # True

匹配多個(gè)字符串開(kāi)頭

''' 學(xué)習(xí)中遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' from urllib.request import urlopen def read_data(name):if name.startswith(("http", "https", "tcp")):return urlopen(name).read()else:with open(name) as f:return f.read()

示例2

filename_list = ["a.png", "b.mp4", "c.txt", "d.pdf"] if any(name.endswith(("png","jpg","jpeg")) for name in filename_list):print("存在圖片")

3.通配符匹配字符串

fnmatch 模塊提供了兩個(gè)函數(shù)—— fnmatch() 和 fnmatchcase() ,可以用來(lái)實(shí)現(xiàn)這樣的匹配

from fnmatch import fnmatch, fnmatchcaseprint(fnmatch("1.txt", "*.txt"))# True print(fnmatch("Day23.csv", "Day[0-9]*"))# True print(fnmatch("hello.txt", "??llo.txt"))# Truefile = ["Day21.txt","Day22.Txt", "uwsgi.ini"] print([name for name in file if fnmatch(name,"Day*.txt")])# ['Day21.txt', 'Day22.txt']# 完全匹配,對(duì)大小寫(xiě)也進(jìn)行驗(yàn)證 print(fnmatchcase("tell.txt","*.TxT"))# False

4.字符串的替換

findall找到所有符合要求數(shù)據(jù)

text = 'UPPER PYTHON, lower python, Mixed Python' result = re.findall("python", text, flags=re.IGNORECASE) print(result)# ['PYTHON', 'python', 'Python']

sub替換字符串

result2 = re.sub('python', 'snake', text, flags=re.IGNORECASE) print(result2)# UPPER snake, lower snake, Mixed snake

替換字符串并不會(huì)自動(dòng)跟被匹配字符串大小寫(xiě)保持一致,為了大小寫(xiě)保持一致可以通過(guò)輔助函數(shù)修復(fù)。

''' 學(xué)習(xí)中遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' def matchcase(word):def replace(m):text = m.group()if text.isupper():return word.upper()elif text.islower():return word.lower()elif text[0].isupper():return word.capitalize()else:return wordreturn replace result3 = re.sub("python", matchcase("snake"), text, flags=re.IGNORECASE) print(result3)# UPPER SNAKE, lower snake, Mixed Snake

5.多行字符串匹配

text1 = '''/* this is a good man */ ''' comment = re.compile(r'/\*((?:.|\n)*?)\*/') print(comment.findall(text1))# [' this is a\ngood man ']

6.扁平數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)樹(shù)形接口

''' 學(xué)習(xí)中遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' lst = [{"id": 1, "name": "dep1", "pid": 0},{"id": 2, "name": "dep2", "pid": 1},{"id": 3, "name": "dep3", "pid": 1},{"id": 4, "name": "dep4", "pid": 2},{"id": 5, "name": "dep5", "pid": 4}, ]def list_to_tree(lst):result = list()mapper = {}for item in lst:id = item["id"]pid = item["pid"]name = item["name"]if not mapper.get("id"):mapper[id] = {"children": []}mapper[id] = {"id": id,"pid": pid,"name": name,"children": mapper[id]["children"]}tree_item = mapper[id]if (pid == 0):result.append(tree_item)else:if not mapper.get(pid):mapper[pid] = {"children": []}mapper[pid]["children"].append(tree_item)return resultres = list_to_tree(lst) print(res)

7.字符串對(duì)

字符串對(duì)齊,除了使用 ljust() , rjust() 和 center() 方法外,還可以使用>, <, ^進(jìn)行填充。

>>> format(text, '>20') ' Hello World' >>> format(text, '<20') 'Hello World ' >>> format(text, '^20') ' Hello World ' # 如果使用非空格填充可以使用 >>> format(text, '=>20s') '=========Hello World' >>> format(text, '*^20s') '****Hello World*****'

總結(jié)

以上是生活随笔為你收集整理的Python基础高级用法,必须要掌握的知识点的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。