大家好,今天我主要来介绍程序当中的通用 Python 代码片段,大家可以收藏、点赞、关注,一起进步吧

废话不多说,我们开始吧,技术交流文末获取

我们先从最常用的数据结构列表开始

№1:将两个列表合并成一个字典

假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值。这是在用 Python 编写代码时经常遇到的一个非常常见的问题

但是为了解决这个问题,我们需要考虑几个限制,比如两个列表的大小,两个列表中元素的类型,以及其中是否有重复的元素,尤其是我们将使用的元素作为 key 时。我们可以通过使用 zip 等内置函数来解决这些问题

keys_list = ['A', 'B', 'C']
values_list = ['blue', 'red', 'bold']#There are 3 ways to convert these two lists into a dictionary
#1- Using Python's zip, dict functionz
dict_method_1 = dict(zip(keys_list, values_list))#2- Using the zip function with dictionary comprehensions
dict_method_2 = {key:value for key, value in zip(keys_list, values_list)}#3- Using the zip function with a loop
items_tuples = zip(keys_list, values_list)
dict_method_3 = {}
for key, value in items_tuples: if key in dict_method_3: pass # To avoid repeating keys.else: dict_method_3[key] = value

№2:将两个或多个列表合并为一个包含列表的列表

另一个常见的任务是当我们有两个或更多列表时,我们希望将它们全部收集到一个大列表中,其中较小列表的所有第一项构成较大列表中的第一个列表

例如,如果我们有 4 个列表 [1,2,3], [‘a’,‘b’,‘c’], [‘h’,‘e’,‘y’] 和 [4,5, 6],我们想为这四个列表创建一个新列表;它将是 [[1,‘a’,‘h’,4], [2,‘b’,‘e’,5], [3,‘c’,‘y’,6]]

def merge(*args, missing_val = None):
#missing_val will be used when one of the smaller lists is shorter tham the others.
#Get the maximum length within the smaller lists.max_length = max([len(lst) for lst in args])outList = []for i in range(max_length):result.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])return outList

№3:对字典列表进行排序

这一组日常列表任务是排序任务,根据列表中包含的元素的数据类型,我们将采用稍微不同的方式对它们进行排序。

dicts_lists = [{"Name": "James","Age": 20,},{"Name": "May","Age": 14,},{"Name": "Katy","Age": 23,}
]#There are different ways to sort that list
#1- Using the sort/ sorted function based on the age
dicts_lists.sort(key=lambda item: item.get("Age"))#2- Using itemgetter module based on name
from operator import itemgetter
f = itemgetter('Name')
dicts_lists.sort(key=f)

№4:对字符串列表进行排序

我们经常面临包含字符串的列表,我们需要按字母顺序、长度或我们想要或我们的应用程序需要的任何其他因素对这些列表进行排序

my_list = ["blue", "red", "green"]#1- Using sort or srted directly or with specifc keys
my_list.sort() #sorts alphabetically or in an ascending order for numeric data
my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest.
# You can use reverse=True to flip the order#2- Using locale and functools
import locale
from functools import cmp_to_key
my_list = sorted(my_list, key=cmp_to_key(locale.strcoll)) 

№5:根据另一个列表对列表进行排序

有时,我们可能需要使用一个列表来对另一个列表进行排序,因此,我们将有一个数字列表(索引)和一个我们想使用这些索引进行排序的列表

a = ['blue', 'green', 'orange', 'purple', 'yellow']
b = [3, 2, 5, 4, 1]
#Use list comprehensions to sort these lists
sortedList =  [val for (_, val) in sorted(zip(b, a), key=lambda x: \x[0])]

№6:将列表映射到字典

列表代码片段的最后一个任务,如果给定一个列表并将其映射到字典中,也就是说,我们想将我们的列表转换为带有数字键的字典

mylist = ['blue', 'orange', 'green']
#Map the list into a dict using the map, zip and dict functions
mapped_dict = dict(zip(itr, map(fn, itr)))

Dictionary Snippets

现在处理的数据类型是字典

№7:合并两个或多个字典

假设我们有两个或多个字典,并且我们希望将它们全部合并为一个具有唯一键的字典

from collections import defaultdict
#merge two or more dicts using the collections module
def merge_dicts(*dicts):mdict = defaultdict(list)for dict in dicts:for key in dict:res[key].append(d[key])return dict(mdict)

№8:反转字典

一个非常常见的字典任务是如果我们有一个字典并且想要翻转它的键和值,键将成为值,而值将成为键

当我们这样做时,我们需要确保没有重复的键。值可以重复,但键不能,并确保所有新键都是可以 hashable 的

my_dict = {"brand": "Ford","model": "Mustang","year": 1964
}
#Invert the dictionary based on its content
#1- If we know all values are unique.
my_inverted_dict = dict(map(reversed, my_dict.items()))#2- If non-unique values exist
from collections import defaultdict
my_inverted_dict = defaultdict(list)
{my_inverted_dict[v].append(k) for k, v in my_dict.items()}#3- If any of the values are not hashable
my_dict = {value: key for key in my_inverted_dict for value in my_inverted_dict[key]}

String Snippets

接下来是字符串的处理

№9:使用 f 字符串

格式化字符串可能是我们几乎每天都需要完成的一项任务,在 Python 中有多种方法可以格式化字符串,使用 f 字符串是比较好的选择

#Formatting strings with f string.
str_val = 'books'
num_val = 15
print(f'{num_val} {str_val}') # 15 books
print(f'{num_val % 2 = }') # 1
print(f'{str_val!r}') # books#Dealing with floats
price_val = 5.18362
print(f'{price_val:.2f}') # 5.18#Formatting dates
from datetime import datetime;
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}') # date_val=2021-09-24

№10:检查子串

一项非常常见的任务就是检查字符串是否在与字符串列表中

addresses = ["123 Elm Street", "531 Oak Street", "678 Maple Street"]
street = "Elm Street"#The top 2 methods to check if street in any of the items in the addresses list
#1- Using the find method
for address in addresses:if address.find(street) >= 0:print(address)#2- Using the "in" keyword
for address in addresses:if street in address:print(address)

№11:以字节为单位获取字符串的大小

有时,尤其是在构建内存关键应用程序时,我们需要知道我们的字符串使用了多少内存

str1 = "hello"
str2 = "												

13 个非常有用的 Python 代码片段,建议收藏相关推荐

  1. 13 个非常有用的 Python 代码片段,建议收藏!

    作者 | 周萝卜 来源 | 萝卜大杂烩 今天我们主要来介绍应用程序当中的通用 Python 代码片段,一起进步吧 Lists Snippets 我们先从最常用的数据结构列表开始 №1:将两个列表合并成 ...

  2. 13个非常有用的Python代码片段

    1:将两个列表合并成一个字典 假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值.这是在用 Python 编写代码时经常遇到的一个非常常见 ...

  3. python语言代码片段-有用的Python代码片段

    我列出的这些有用的Python代码片段,为我节省了大量的时间,并且我希望他们也能为你节省一些时间.大多数的这些片段出自寻找解决方案,查找博客和StackOverflow解决类似问题的答案.下面所有的代 ...

  4. 25个好用到爆的一行 Python 代码,建议收藏

    作者 | 欣一 来源 | Pyhton爱好集中营 在学习Python的过程当中,有很多复杂的任务其实只需要一行代码就可以解决,那么今天小编我就来给大家介绍实用的一行Python代码,希望对大家能够有所 ...

  5. 20 条非常实用的 Python 代码,建议收藏!

    [欢迎关注微信公众号:厦门微思网络] 微思网络(官网):https://www.xmws.cn/ 据说Python之父-Guido Van Rossum打算让CPython更快,速度直接翻五倍,这是实 ...

  6. 【Python】25个好用到爆的一行Python代码,建议收藏

    在学习Python的过程当中,有很多复杂的任务其实只需要一行代码就可以解决,那么今天小编我就来给大家介绍20个实用的一行Python代码,希望对大家能够有所帮助. 1.两个字典的合并 x = {'a' ...

  7. 25个好用到爆的一行Python代码,建议收藏

    大家好,我是欣一 在学习Python的过程当中,有很多复杂的任务其实只需要一行代码就可以解决,那么今天小编我就来给大家介绍20个实用的一行Python代码,希望对大家能够有所帮助. 1.两个字典的合并 ...

  8. [转载] 50个数据可视化最有价值的图表(附完整Python代码,建议收藏)

    参考链接: 使用Python中的不同图表进行数据可视化 本文总结了 Matplotlib 以及 Seaborn 用的最多的50个图形,掌握这些图形的绘制,对于数据分析的可视化有莫大的作用,强烈推荐大家 ...

  9. 50个数据可视化最有价值的图表(附完整Python代码,建议收藏

    上:https://www.jianshu.com/p/8809846ccd9a?utm_campaign=haruki&utm_content=note&utm_medium=rea ...

最新文章

  1. bat 连续读取两行_Redis底层数据结构解析(BAT大厂必问)
  2. php浏览服务器某一文件夹内容,php删除web服务器中指定目录下的指定格式的文件...
  3. 神操作!员工索要工资遭遇“假转账”:转了生气又撤销
  4. 关于golden gate director client的一点点使用总结
  5. 热点争议:Web设计师需要编程知识吗?
  6. C++ log4cpp(tx2)
  7. 北斗时钟同步服务器,电力系统卫星时钟-GPS北斗时钟方案
  8. 使用strace查看后台程序stdout输出
  9. matlab读取sgy格式文件的m文件,matlab读取segy格式的文件
  10. ios - 农历公历互转 农历选择器
  11. 【Java程序设计】GUI程序设计(设计封装矩形类、利用监听事件对textField进行读取和输入)
  12. 算法系列——弗洛伊德算法(Floyd)
  13. CSS制作各种三角形写法
  14. 图像增强(拉普拉斯锐化增强)
  15. 【数学建模】“华为杯”高级神经网络Keras(Python代码实现)
  16. 基于spring boot的毕业设计论文选题申报管理系统设计与实现 毕业论文+项目源码、
  17. Mobileye在耶路撒冷启动自动驾驶测试,挑战极限路况
  18. 建筑信息化模型BIM经典《BIM Handbook》中文翻译第一章第二节(持续更新)
  19. 百度云非 VIP如何作弊加速?
  20. 淘宝大秒杀系统设计详解

热门文章

  1. php邮件回复功能,用PHP回复邮件(Laravel Mailgun)
  2. Kubernetes 集群安全机制详解
  3. 阿里巴巴对工业互联网志在必得,阿里云如何啃硬骨头?
  4. 后补贴时代-新能源车企商业模式之“柳州模式”
  5. 手机设备唯一标识相关概念
  6. how to get SoCs and devices information in QEMU
  7. 做跨境电商的Anker的也回来“内卷”了?
  8. 人工智能 漆桂林_2020年CCF专委活动计划(预通过)
  9. C3AE: Exploring the Limits of Compact Model for Age Estimation
  10. 华为有线无线组网案例