996 一直是互联网老生常谈的话题了,但抛开其他只谈工作本身,你有没有想过,下班晚、加班,有时候可能是因为自己工作比较低效?

大家好,今天周末,整理的25个常用的Python代码段,平时多积累好用、常用、简洁的代码段真的非常有必要。喜欢记得收藏、点赞、关注。

注:完整代码、资料、技术沟通,文末获取

1交换两个变量的值

num_1, num_2 = 666, 999
# 一行代码搞定交换两个变量的值
num_1, num_2 = num_2, num_1
print(num_1, num_2)
输出:
999 666Process finished with exit code 0

2查找对象使用的内存

import sysslogan = "今天你学python了么?"
size = sys.getsizeof(slogan)
print(size)
输出:
100Process finished with exit code 0

3反转字符串

slogan = "今天你学习python了么?"
# 一行代码搞定字符串的反转
new_slogan = slogan[::-1]
print(new_slogan)
输出:
?么了nohtyp习学你天今
Process finished with exit code 0

4检查字符串是否为回文

# 定义一个判断字符串是否是回文的函数
def is_palindrome(string):return string == string[::-1]示例:调用判断函数来进行判断slogan是否是回文字符串
slogan = "今天你学python了么?"
_ = is_palindrome(slogan)
print(_)
输出:
FalseProcess finished with exit code 0

5将字符串列表合并为单个字符串

slogan = ["今", "天", "你", "学", "python", "了", "么", "?"]
# 一行代码搞定将字符串列表合并为单个字符串
real_slogan = "".join(slogan)
print(real_slogan)
输出:
今天你学python了么?Process finished with exit code 0

6查找存在于两个列表中任一列表存在的元素

# 定义一个函数用来查找存在于两个列表中任一列表存在的元素
def union(list1, list2):return list(set(list1 + list2))示例:调用该函数用来查找存在于两个列表中任一列表存在的元素
list1, list2 = [5, 2, 0], [5, 2, 1]
new_list = union(list1, list2)
print(new_list)
输出:
[0, 1, 2, 5]Process finished with exit code 0

7打印N次字符串

slogan = "今天你学python了么?"
new_slogan = 11*slogan
print(new_slogan)
输出:
今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?Process finished with exit code 0

8链式比较

number = 100
print(98<number<102)
输出:
TrueProcess finished with exit code 0print(100==number<102)
输出:
TrueProcess finished with exit code 0

9单词大小写

slogan = "python happy"
# 一行代码搞定单词大小写转换
print(slogan.upper())# 一行代码搞定单词首字母大写
print(slogan.capitalize())# 一行代码搞定将每个单词的首字母转为大写,其余小写
print(slogan.title())
输出:
PYTHON HAPPY
Python happy
Python HappyProcess finished with exit code 0

10统计列表中元素的频率

from collections import Counternumbers = [1, 1, 3, 2, 4, 4, 3, 6]
# 一行代码搞定求列表中每个元素出现的频率
count = Counter(numbers)
print(count)
输出:
Counter({1: 2, 3: 2, 4: 2, 2: 1, 6: 1})Process finished with exit code 0

11判断字符串所含元素是否相同

from collections import Countercourse = "python"
new_course = "ypthon"
count_1, count_2 = Counter(course), Counter(new_course)
if count_1 == count_2:print("两个字符串所含元素相同!")
输出:
两个字符串所含元素相同!Process finished with exit code 0

12将数字字符串转化为数字列表

string = "666888"
numbers = list(map(int, string))
print(numbers)
输出:
[6, 6, 6, 8, 8, 8]Process finished with exit code 0

13使用enumerate() 函数来获取索引-数值对

string = "python"
for index, value in enumerate(string):print(index, value)
输出:
0 p
1 y
2 t
3 h
4 o
5 nProcess finished with exit code 0

14代码执行消耗时间

import timestart_time = time.time()numbers = [i for i in range(10000)]end_time = time.time()
time_consume = end_time - start_time
print("代码执行消耗的时间是:{}".format(time_consume))
输出示例:
代码执行消耗的时间是:0.002994537353515625Process finished with exit code 0

15比较集合和字典的查找效率

import timenumber = 999999
# 生成数字列表和数字集合
numbers = [i for i in range(1000000)]
digits = {i for i in range(1000000)}start_time = time.time()
# 列表的查找
_ = number in numbers
end_time = time.time()print("列表查找时间为:{}".format(end_time - start_time))start_time = time.time()
# 集合的查找
_ = number in digits
end_time = time.time()print("集合查找时间为:{}".format(end_time - start_time))
输出:
列表查找时间为:0.060904741287231445
集合查找时间为:0.0Process finished with exit code 0

16字典的合并

info_1 = {"apple": 13, "orange": 22}
info_2 = {"爆款写作": 48, "跃迁": 49}
# 一行代码搞定合并两个字典
new_info = {**info_1, **info_2}
print(new_info)
输出:
{'apple': 13, 'orange': 22, '爆款写作': 48, '跃迁': 49}
Process finished with exit code 0

17随机采样

import randombooks = ["爆款写作", "这个世界,偏爱会写作的人", "写作七堂课", "越书写越明白"]
# 随机取出2本书阅读
reading_book = random.sample(books, 2)
print(reading_book)
输出:
['这个世界,偏爱会写作的人', '越书写越明白']Process finished with exit code 0

18判断列表中元素的唯一性

# 定义一个函数判断列表中元素的唯一性
def is_unique(list):if len(list) == len(set(list)):return Trueelse:return False# 调用该函数判断一个列表是否是唯一性的
numbers = [1, 2, 3, 3, 4, 5]
_ = is_unique(numbers)
print(_)
输出:
False
Process finished with exit code 0

19计算阶乘 递归函数实现

def fac(n):if n > 1:return n*fac(n-1)else:return 1number = int(input("n="))
print("result = {}".format(fac(number)) )
输出:
n=5
result = 120Process finished with exit code 0

20列出当前目录下的所有文件和目录名

import osfiles = [file for file in os.listdir(".")]
print(files)
输出:
['.idea', '2048.py', 'access.log', 'beautiful_girls', 'beautiful_girls_photos', 'boy.py', 'cache.json', 'catoffice.py', 'cookie.json', 'data.csv', 'data.txt', 'diary', 'files', 'filtered_words.txt', 'geckodriver.log', 'get_movies_info2.py', 'girl.py', 'girl1.py', 'ha.conf', 'homework.py', 'homework3.py', 'index.html', 'info.ini', 'notepad.py', 'rent.csv', 'stock.txt', 'student.txt', 'student.xlsx', 'student_register_info.json', 'test.png', 'test_picture.txt', 'zhihu.html', '__pycache__', '九尾1997_200行代码实现2048小游戏.py', '九尾1997_python实现图片转字符画.py', '九尾1997_实现一个简单的计算器.py', '九尾1997_爬取优美图美女写真.py', '九尾1997_爬取北京58租房信息.py', '九尾1997_路飞学城注册页面', '校园管理系统.py', '爬虫模拟登录.py', '记事本.m4a']Process finished with exit code 0

21把原字典的键值对颠倒并生产新的字典

dict_1 = {1: "python", 2: "java"}
new_dict = {value:key for key, value in dict_1.items()}
print(new_dict)
输出:
{'python': 1, 'java': 2}Process finished with exit code 0

22打印九九乘法表

for i in range(1, 10):for j in range(1, i+1):print("{} * {} = {}".format(i, j, i*j), end="")print()
输出:
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 Process finished with exit code 0

23计算每个月天数

import calendarmonth_days = calendar.monthrange(2025,8)
print(month_days)
输出:
(4, 31)Process finished with exit code 0

24随机生成验证码,调用随机模块

import random, stringstr_1 = "0123456789"
# str_2 是包含所有字母的字符串
str_2 = string.ascii_letters
str_3 = str_1 + str_2
# 多个字符中选取特定数量的字符
verify_code = random.sample(str_3, 6)
# 使用join方法拼接转换为字符串
verify_code = "".join(verify_code)
print(verify_code)
输出:
Mk0L6YProcess finished with exit code 0

25判断闰年

year  = input("请输入一个年份:")
year = int(year)
# 一行代码判断年份是否是闰年
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:print("{}是闰年!".format(year))
else:print("{}不是闰年!".format(year))
输出示例:
请输入一个年份:2000
2000是闰年!Process finished with exit code 0

推荐文章

  • 李宏毅《机器学习》国语课程(2022)来了

  • 有人把吴恩达老师的机器学习和深度学习做成了中文版

  • 上瘾了,最近又给公司撸了一个可视化大屏(附源码)

  • 如此优雅,4款 Python 自动数据分析神器真香啊

  • 梳理半月有余,精心准备了17张知识思维导图,这次要讲清统计学

  • 香的很,整理了20份可视化大屏模板

技术交流

欢迎转载、收藏、有所收获点赞支持一下!

目前开通了技术交流群,群友已超过2000人,添加时最好的备注方式为:来源+兴趣方向,方便找到志同道合的朋友

  • 方式①、发送如下图片至微信,长按识别,后台回复:加群;
  • 方式②、添加微信号:dkl88191,备注:来自CSDN
  • 方式③、微信搜索公众号:Python学习与数据挖掘,后台回复:加群

推荐收藏,25条实用简洁的 Python 代码真香啊相关推荐

  1. 25条实用的Python一行代码,你用过哪些?

    自从我用Python编写第一行代码以来,就被它的简单性.出色的可读性和特别流行的一行代码所吸引. 在下面,我将给大家介绍并解释一些非常实用Python一行程序. 可能有些你还不知道,但对你未来的Pyt ...

  2. python中如何编写代码输入多个数据并把它们放在一个列表中去_这59条编写高质量Python代码的方法你知道吗?...

    这个周末断断续续的阅读完了<Effective Python之编写高质量Python代码的59个有效方法>,感觉还不错,具有很大的指导价值. 下面将以最简单的方式记录这59条建议,并在大部 ...

  3. BPR贝叶斯个性化推荐算法—推荐系统基础算法(含python代码实现以及详细例子讲解)

    BPR贝叶斯个性化排序算法 一.问题导入 二.显示反馈与隐式反馈 2.1 显式反馈与隐式反馈基本概念 2.2 显式反馈与隐式反馈的比较 2.3 显式反馈与隐式反馈的评价方法 2.3.1 显式反馈数据模 ...

  4. 3000 字推荐一个可视化神器,50 行 Python 代码制作数据大屏

    作者 | 俊欣 来源 | 关于数据分析与可视化 今天小编给大家分享一个制作数据大屏的工具,非常的好用,100行左右的Python代码就可以制作出来一个完整的数据大屏,并且代码的逻辑非常容易理解. Py ...

  5. 7-24 树种统计 (25 分)(详解)map做法 map真香啊!

    一:题目 7-24 树种统计 (25 分) 随着卫星成像技术的应用,自然资源研究机构可以识别每一棵树的种类.请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比. 输入格式: 输入首先给出 ...

  6. 推荐两个非常实用的,Python装饰器

    1.超时函数 这个函数的作用在于可以给任意可能会hang住的函数添加超时功能,这个功能在编写外部API调用 .网络爬虫.数据库查询的时候特别有用 timeout装饰器的代码如下: import sig ...

  7. 【实用篇】Python代码编写规范

    今天我们来讲述一下Python的编码规范,通过详细对代码编写规则以及命名规范等进行介绍. 1.编写规则 Python采用PEP 8 的编码规范,接下来会讲解一些我们在学习Python过程应该严格遵守的 ...

  8. 25个Matplotlib图的Python代码,复制直接可用

    今天分享给大家25个Matplotlib图的汇编,在数据分析和可视化中最有用. # !pip install brewer2mpl import numpy as np import pandas a ...

  9. ArcGIS利用数据驱动工具条批量出图(python代码)

    一.设置数据驱动 参考文章: ArcGIS高级制图及批量出图使用数据驱动 二.在工作空间自动生成图片 1.PDF批量出图 参考阅读:ArcGIS批量出图操作流程(附练习数据下载) 目前在ArcGIS1 ...

最新文章

  1. Gmapping从开始到放弃—写一个TF 监听
  2. 手把手教 | 深度学习库PyTorch(附代码)
  3. 在python中、下列代码的输出是什么-python期末考试试题汇总
  4. T-SQL编程基础之一:变量与基本语句
  5. java fix_Java中的低延迟FIX引擎
  6. C++工作笔记-结构体与类的进一步探究(在C++中的结构体,非C语言结构体)
  7. uni-app + vue-cli3 安装axios、vant等依赖 - 操作篇
  8. ConfirmCancelUtilDialog【确认取消对话框封装类】
  9. 北京严厉打击违规发布网络房源信息行为 18家机构被查处
  10. django 笔记3
  11. 苹果xsmax怎么开机_苹果XS/xs max按钮浮标怎么设置?
  12. 邻接矩阵实现无向图的创建并根据louvain算法实现分区
  13. 程序员面试:未来五年的规划是怎样的?
  14. linux系统下部署python自动化程序并配置Jenkins定时执行
  15. 免费服务器搭建--个人网站搭建第一步
  16. SQLite3的安装使用
  17. 化妆行业网站建设方案
  18. python入门之python编程语言(简介)
  19. Fiddler工具 — Fiddler过滤器(Filters)详解
  20. 京瓷1800打印机扫描步骤_京瓷1800操作指南

热门文章

  1. 快递扫码系统php,菜鸟驿站又出黑科技,实现扫码秒取快递
  2. Android PDF原生实现 PDF阅读、PDF手势伸缩、PDF目录、PDF预览缩略图 PDF方案选择 google doc android-pdfview mupdf pdf.js x5
  3. win10字体模糊怎么调节
  4. 高斯分布——在误差测量中的推导
  5. 南邮计算机学院研究生导师,南京邮电大学计算机/软件学院导师介绍:肖甫
  6. 火狐浏览器占用过多内存
  7. springboot 自定义filter
  8. matlab显示tiff为全白_请教Matlab图片如何转换成TIFF
  9. 高德地图API简单使用——地名转经纬度
  10. 【Esp32】用esp32和max30102制作一个血氧仪