1.ChainMap
当我们有2个字段o1
和o2
你想将它们从合并后进行查找操作(比如先从o1
找,如果o1
找不到,再去o2
找),如下:
from collections import ChainMap
o1 = {"a" : 1 , "c" : 10 }
o2 = {"b" : 5 , "c" : 4 }
o3 = ChainMap(o1, o2)
print (o3)
print (o3["a" ])
print (o3["b" ])
print (o3["c" ])
print (o3.get("d" ))
当然o3
也具备字典的特性,我们通过删除,更新,添加操作总是优先影响第一个字典
o3["c" ] = 100
print (o3)
print (o1)
del o3["c" ]
print (o3)
o3["d" ] = 20
print (o3)
values = ChainMap()
values["x" ] = 1
values = values.new_child()
values["x" ] = 2
values = values.new_child()
values["x" ] = 3
print (values)
print (values["x" ])
values = values.parents
print (values)
print (values["x" ])
values = values.parents
print (values["x" ])
2.字符串开口结尾匹配
一般我们匹配字符串以开头或结尾用的方法是: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))
print (any (name.endswith(".py" ) for name in lst2))
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()
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
模块提供了两个函数—— fnmatch()
和 fnmatchcase()
,可以用来实现这样的匹配
from fnmatch import fnmatch, fnmatchcase
print (fnmatch("1.txt" , "*.txt" ))
print (fnmatch("Day23.csv" , "Day[0-9]*" ))
print (fnmatch("hello.txt" , "??llo.txt" ))
file = ["Day21.txt" ,"Day22.Txt" , "uwsgi.ini" ]
print ([name for name in file if fnmatch(name,"Day*.txt" )])
print (fnmatchcase("tell.txt" ,"*.TxT" ))
4.字符串的替换
text = 'UPPER PYTHON, lower python, Mixed Python'
result = re.findall("python" , text, flags=re.IGNORECASE)
print (result)
result2 = re.sub('python' , 'snake' , text, flags=re.IGNORECASE)
print (result2)
替换字符串并不会自动跟被匹配字符串大小写保持一致,为了大小写保持一致可以通过辅助函数修复。
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 word
return replace
result3 = re.sub("python" , matchcase("snake" ), text, flags=re.IGNORECASE)
print (result3)
5.多行字符串匹配
text1 = '''/* this is a
good man */
'''
comment = re.compile (r'/\*((?:.|\n)*?)\*/' )
print (comment.findall(text1))
6.扁平数据结构转树形接口
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 result
res = list_to_tree(lst)
print (res)
7.字符串对
字符串对齐,除了使用 ljust()
, rjust()
和 center()
方法外,还可以使用>
, <
, ^
进行填充。
>>> 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*****'
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库