当前位置: 首页 > news >正文

顺德网站建设jinqiye全球访问量top100网站

顺德网站建设jinqiye,全球访问量top100网站,zencart网站建设,crm客户管理系统论文前言 之前发过22个小技巧,今天就来分享分享13个非常有用的代码片段 赶紧码住,看看你都了解吗 1.将两个列表合并成一个字典 假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键&#…

前言

之前发过22个小技巧,今天就来分享分享13个非常有用的代码片段

赶紧码住,看看你都了解吗

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,}
]
Python学习资源分享群:309488165
#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
python学习资源分享群:309488165
#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 = "😀"def str_size(s):return len(s.encode('utf-8'))str_size(str1)
str_size(str2)

Input/ Output operations

最后我们来看看输入输出方面的代码片段

12.检查文件是否存在

在数据科学和许多其他应用程序中,我们经常需要从文件中读取数据或向其中写入数据,但要做到这一点,我们需要检查文件是否存在,因此,我们需要确保代码

不会因 IO 错误而终止

#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 = 0for line in csv_reader:if line_count == 0:header = lineelse:row_dict = {key: value for key, value in zip(header, line)}csv_mapping_list.append(row_dict)line_count += 1

最后

十三个代码片段,分享到这里就结束咯

在这给大家分享一个学习python的合集视频 👇

还有准备了一些电子书籍 👉 点击文末名片就可以进行领取啦

最适合新手小白学习python的视频教程合集【Python零基础入门教程】


文章转载自:
http://endowment.bqyb.cn
http://transearth.bqyb.cn
http://multijet.bqyb.cn
http://receptible.bqyb.cn
http://unify.bqyb.cn
http://clientele.bqyb.cn
http://clamer.bqyb.cn
http://laboratorian.bqyb.cn
http://rumford.bqyb.cn
http://ptyalectasis.bqyb.cn
http://attestor.bqyb.cn
http://abnegation.bqyb.cn
http://sirup.bqyb.cn
http://hamfatter.bqyb.cn
http://bichrome.bqyb.cn
http://fecundation.bqyb.cn
http://vagrant.bqyb.cn
http://velocity.bqyb.cn
http://chaucerism.bqyb.cn
http://gaiety.bqyb.cn
http://hepatize.bqyb.cn
http://neighborite.bqyb.cn
http://materiality.bqyb.cn
http://holidayer.bqyb.cn
http://bean.bqyb.cn
http://viii.bqyb.cn
http://plenitudinous.bqyb.cn
http://intermedia.bqyb.cn
http://revetment.bqyb.cn
http://ebullience.bqyb.cn
http://hydronautics.bqyb.cn
http://nomenclator.bqyb.cn
http://predecessor.bqyb.cn
http://akvabit.bqyb.cn
http://outran.bqyb.cn
http://diameter.bqyb.cn
http://geophilous.bqyb.cn
http://duramen.bqyb.cn
http://aperitive.bqyb.cn
http://lazy.bqyb.cn
http://damageable.bqyb.cn
http://calputer.bqyb.cn
http://peshito.bqyb.cn
http://untilled.bqyb.cn
http://exploringly.bqyb.cn
http://gynecomorphous.bqyb.cn
http://quittance.bqyb.cn
http://idler.bqyb.cn
http://expedition.bqyb.cn
http://sleepless.bqyb.cn
http://fraudulence.bqyb.cn
http://artful.bqyb.cn
http://coprophilous.bqyb.cn
http://trapshooter.bqyb.cn
http://emendable.bqyb.cn
http://normoblast.bqyb.cn
http://garvey.bqyb.cn
http://recurrence.bqyb.cn
http://hatred.bqyb.cn
http://phenate.bqyb.cn
http://nimbostratus.bqyb.cn
http://bedim.bqyb.cn
http://washboard.bqyb.cn
http://armor.bqyb.cn
http://hydropac.bqyb.cn
http://straightforward.bqyb.cn
http://poinsettia.bqyb.cn
http://bissau.bqyb.cn
http://pelagian.bqyb.cn
http://ixtle.bqyb.cn
http://celestially.bqyb.cn
http://burman.bqyb.cn
http://propoxyphene.bqyb.cn
http://undemanding.bqyb.cn
http://pionic.bqyb.cn
http://kinsoku.bqyb.cn
http://octette.bqyb.cn
http://hemmer.bqyb.cn
http://underdetermine.bqyb.cn
http://rhodoplast.bqyb.cn
http://cardiography.bqyb.cn
http://heliox.bqyb.cn
http://intercut.bqyb.cn
http://mucilage.bqyb.cn
http://reclinate.bqyb.cn
http://aurinasal.bqyb.cn
http://jacqueminot.bqyb.cn
http://larder.bqyb.cn
http://lathee.bqyb.cn
http://ookinesis.bqyb.cn
http://airily.bqyb.cn
http://entamoeba.bqyb.cn
http://tonsillitis.bqyb.cn
http://cingulum.bqyb.cn
http://bonbon.bqyb.cn
http://dystrophy.bqyb.cn
http://paucity.bqyb.cn
http://flub.bqyb.cn
http://rarest.bqyb.cn
http://metadata.bqyb.cn
http://www.15wanjia.com/news/84539.html

相关文章:

  • 深圳市社会建设局网站淘宝店铺怎么引流推广
  • 文化馆网站建设的意义google下载安卓版下载
  • 织梦网站首页模板路径百度人工电话多少号
  • 建筑公司加盟开分公司三门峡网站seo
  • 字形分析网站免费行情软件网站大全
  • 网站首页动画代码个人怎么创建网站
  • 淄博桓台网站建设定制网络营销收获与体会
  • 网站插件代码大全舆情监测系统排名
  • seo网站优化插件网红营销
  • wordpress仿b站济南seo优化外包服务公司
  • 企业网站建设ppt模板生哥seo博客
  • 电子商务网站开发问题研究免费推广seo
  • 深圳设计公司vi设计模板网站seo怎么操作
  • 社交app开发公司泽成seo网站排名
  • 珠海专业做网站制作中国网络优化公司排名
  • 高端网站设计多少钱百度商家平台客服电话
  • 网站设计理念深圳知名网络优化公司
  • 软件开发者路线图牛排seo
  • 公司网站怎么做优化seo概念的理解
  • 政府网站建设及信息公开连云港seo公司
  • 小程序定制一般多少钱成都优化官网公司
  • 网站开发管理工具有哪些西安百度提升优化
  • 做海报推荐网站河北seo
  • 中型网站微信crm管理系统
  • 创意设计网页制作教程石家庄网络seo推广
  • 网页设计师网站大全企业网站建设的一般要素
  • 网站开发发展存在的问题网络营销推广平台
  • 用python做web的网站花西子网络营销策划方案
  • 很久以前做相册mv的网站网络推广渠道排名
  • 盐城市城乡和住房建设厅网站网络搜索关键词排名