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) # ChainMap({'a': 1, 'c': 10}, {'b': 5, 'c': 4})
print(o3["a"])
print(o3["b"])
print(o3["c"])
# 如果查寻一个不存在的key通过[]会报错,我们可以通过get方式更缓和一点
print(o3.get("d")) # None
- 当然
o3
也具备字典的特性,我们通过删除,更新,添加操作总是优先影响第一个字典
# 更新
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})
values = ChainMap()
values["x"] = 1
# 新建一个空的映射对象
values = values.new_child()
values["x"] = 2
values = values.new_child()
values["x"] = 3
print(values) # ChainMap({'x': 3}, {'x': 2}, {'x': 1})
print(values["x"]) # 3
# 类似列表中取 [1:]切片
values = values.parents
print(values)# ChainMap({'x': 2}, {'x': 1})
print(values["x"])# 2
values = values.parents
print(values["x"]) # 1
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)) # False
print(any(name.endswith(".py") for name in lst2)) # True
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"))# True
print(fnmatch("Day23.csv", "Day[0-9]*"))# True
print(fnmatch("hello.txt", "??llo.txt"))# True
file = ["Day21.txt","Day22.Txt", "uwsgi.ini"]
print([name for name in file if fnmatch(name,"Day*.txt")])# ['Day21.txt', 'Day22.txt']
# 完全匹配,对大小写也进行验证
print(fnmatchcase("tell.txt","*.TxT"))# False
4.字符串的替换
text = 'UPPER PYTHON, lower python, Mixed Python'
result = re.findall("python", text, flags=re.IGNORECASE)
print(result)# ['PYTHON', 'python', 'Python']
result2 = re.sub('python', 'snake', text, flags=re.IGNORECASE)
print(result2)# UPPER snake, lower snake, Mixed snake
- 替换字符串并不会自动跟被匹配字符串大小写保持一致,为了大小写保持一致可以通过辅助函数修复。
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)# 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.扁平数据结构转树形接口
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*****'