python实用操作

网友投稿 621 2022-11-26

python实用操作

python实用操作

将两个字段内容合并成一个字典

>>> a = ["id", "name", "score"]>>> b = [[1, "name_1", "socre_1"],[2, "name_2", "socre_2"]]>>> c = []>>> for record in b: c.append(dict(zip(a, record)))>>> c[{'name': 'name_1', 'score': 'socre_1', 'id': 1}, {'name': 'name_2', 'score': 'socre_2', 'id': 2}]

对列表正序和倒序排序

>>> a = [4,5,3,7,2,9,8,1,0]>>> a.sort()>>> a[0, 1, 2, 3, 4, 5, 7, 8, 9]>>> a.sort(reverse=True)>>> a[9, 8, 7, 5, 4, 3, 2, 1, 0]>>> b = [4,5,3,7,2,9,8,1,0]>>> print(sorted(b))[0, 1, 2, 3, 4, 5, 7, 8, 9]>>> b[4, 5, 3, 7, 2, 9, 8, 1, 0]>>> print(sorted(b, reverse=True))[9, 8, 7, 5, 4, 3, 2, 1, 0]>>> b[4, 5, 3, 7, 2, 9, 8, 1, 0]

lambda表达式对元素为字典的列表排序

>>> a = [{"name":"name_01", "age":12},{"name":"name_02", "age":10},{"name":"name_03", "age":15}]>>> a.sort(key=lambda x:x["age"])>>> a[{'name': 'name_02', 'age': 10}, {'name': 'name_01', 'age': 12}, {'name': 'name_03', 'age': 15}]

字典与与json字符串转换

>>> d = {"a":1, "b":2, "c":3}>>> import json>>> json_str = json.dumps(d) # dict-》json>>> print(json_str, type(json_str)){"b": 2, "a": 1, "c": 3} >>> a = json.loads(json_str)>>> print(a, type(a)){'b': 2, 'a': 1, 'c': 3}

正则表达式

match用于匹配,search用于搜索>>> re.match("hello", "ahello") #匹配不到>>> re.match(".*hello", "ahello") #可以匹配到<_sre.SRE_Match object; span=(0, 6), match='ahello'>>>> re.search("hello", "ahello") #可以搜索到<_sre.SRE_Match object; span=(1, 6), match='hello'>

用正则表达式查找字符串中所有email,所有email域名是.com或-,不区分大小写>>> ls = "邮箱是123@163.com,还是xyz@122.com,或者是abc@qq.com">>> prefix = "[0-9a-zA-Z]+@[0-9a-zA-Z]+\.">>> lt = re.findall(prefix+"com|"+prefix+"net", ls, re.I) #re.I为不区分大小写>>> lt['123@163.com', 'xyz@122.com', 'abc@qq.com']

提取url>>> ls = ">> for url in lt: print(url)copy:只复制深层对象的引用 deepcopy:复制深层对象本身

>>> import copy>>> a = [1,2,3,4,['a','b']]>>> c = copy.copy(a) # 浅拷贝>>> d = copy.deepcopy(a) # 深拷贝>>> a.append(5)>>> c[1, 2, 3, 4, ['a', 'b']]>>> d[1, 2, 3, 4, ['a', 'b']]>>> a[1, 2, 3, 4, ['a', 'b'], 5]>>> a[4].append('c')>>> a[1, 2, 3, 4, ['a', 'b', 'c'], 5]>>> c[1, 2, 3, 4, ['a', 'b', 'c']]>>> d[1, 2, 3, 4, ['a', 'b']]

soup获取所有指定标签的内容

from bs4 import BeautifulSoupimport requestsr = requests.get("= r.apparent_encodingsoup = BeautifulSoup(r.text, "html.parser")print(soup.prettify())lt = []for a in soup.find_all('a'): lt.append(a)print(lt)

datetime计算日期

>>> import datetime>>> a = datetime.date(1990, 1, 3)>>> delta = datetime.timedelta(30)>>> b = a + delta>>> bdatetime.date(1990, 2, 2)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:UVA 10791 Minimum Sum LCM(算术基本定理)
下一篇:操作系统课笔记
相关文章

 发表评论

暂时没有评论,来抢沙发吧~