Python人一定要知道的13个代码片段(超有用,拒绝标题党!)

本文介绍了13个对Python开发者非常有用的代码片段,包括合并列表成字典、多列表合并、字典列表排序、字符串排序、基于列表排序、列表转字典、字典合并与反转、f-string格式化、子串检查、字符串字节大小、文件存在检查和CSV解析。这些片段旨在提高编程效率和代码质量。
摘要由CSDN通过智能技术生成

Python人一定要知道的13个超有用的代码片段,这些日常片段将优化你的Python编程代码

当你每天使用Python来解决挑战、开发算法和构建应用程序时,你会发现自己在不断地重复一些任务。这就是为什么为通常执行的任务准备一些代码片段是一个很好的选择,这样你就可以在需要时直接在你的项目中使用它们。

列表式片段,我认为是 Python 最常用的数据结构–列表的片段开始。

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

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

思考如何建立一本袖珍的黄页,例如:119是火警电话;110:报警电话等;字典是高效直观的数据结构,数据查询量极大的时候,字典的查询效率很高;

tel = [‘110’,‘119’] service = [‘报警’,‘火警’]

如何合并两个列表成为字典:

tel_service = {‘110’:‘报警’ ‘119’:‘火警’}

并且注意合并两个列表的长度是否一致?

列表的元素是否unique:是否唯一没有重复出现?

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  

但是要解决这个问题,我们需要考虑一些限制,比如两个列表的大小,两个列表中的项目类型,以及其中是否有重复的项目,特别是在我们将用作键的列表中。我们可以通过使用像zip这样的内置函数来克服这个问题。

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

另一个常见的任务是当我们有两个或更多的列表时,我们想把它们都收集到一个大的列表中,其中小列表的所有第一项构成大列表的第一项。

例如,如果我有4个列表

[1,2,3],   
['a', 'b', 'c'],   
['h', 'e', 'y'],   
[4,5,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  

它将是:

[[1, 'a', 'h',4], [2, 'b', 'e',5], [3, 'c', 'y', 6]]  

№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)))  

字典片段 下面我们要解决的数据类型是字典。

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

前方高能:using the collections module

假设我们有两个或更多的字典,我们想把它们都合并成一个具有唯一键的字典。

from collections import defaultdict  
#合并两个或多个字典  
#merge two or more dicts using the collections module  
def merge_dicts(*dicts):  
  mdict = defaultdict(list)  
  for d in dicts:  
    for key in d:  
      mdict[key].append(d[key])  
  return dict(mdict)  

№8: 倒置一个字典

一个很常见的字典任务是,如果我们有一个字典,想把它的键和值翻转过来。所以,键会变成值,而值会变成键。

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]}  

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

字符串摘录

№9:使用fstring 字符串

格式化字符串可能是你几乎每天都需要做的头号任务。在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: 检查子串

我以前多次需要执行的一个非常普通的任务是检查一个字符串是否在一个字符串的列表中。
方法1:

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:

#2- Using the "in" keyword   
for address in addresses:  
    if street in address:  
        print(address)  

№11: 获取字符串的字节大小

有时,特别是在构建内存关键型的应用程序时,我们需要知道我们的字符串使用了多少内存。幸运的是,这可以通过一行代码快速完成。

str1 = "hello"  
str2 = "😀"  
  
def str_size(s):  
  return len(s.encode('utf-8'))  
  
str_size(str1)  
str_size(str2)  

输入/输出操作

№12: 检查一个文件是否存在

在数据科学和其他许多应用中,我们经常需要从文件中读取数据或向文件中写入数据。但要做到这一点,我们需要检查一个文件是否存在。这样,我们的代码就不会因错误而终止。

#Checking if a file exists in two ways  
#1- Using the OS module  
import os   
exists = os.path.isfile('/path/to/file')  
  
#2- Use the pathlib module for a better performance  
from pathlib import Path  
config = Path('/path/to/file')   
if config.is_file():   
    pass  

№13:解析一个电子表格

另一个非常常见的文件交互是解析电子表格的数据。幸运的是,我们有CSV模块来帮助我们有效地完成这项任务。

import csv  
csv_mapping_list = []  
with open("/path/to/data.csv") as my_data:  
    csv_reader = csv.reader(my_data, delimiter=",")  
    line_count = 0  
    for line in csv_reader:  
        if line_count == 0:  
            header = line  
        else:  
            row_dict = {key: value for key, value in zip(header, line)}  
            csv_mapping_list.append(row_dict)  
        line_count += 1  

在这篇文章中,我们一起走过了这些代码片段中的13个,你可以把它们添加到你的代码片段数据库中,或者开始一个新的数据库。这些代码片段简单、简短、高效,无论你在哪个应用领域工作,你最终都会在任何Python项目中至少使用其中一个。希望你能发现它们的帮助。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值