日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
13個(gè)非常有用的Python代碼片段,建議收藏!

Lists Snippets

我們先從最常用的數(shù)據(jù)結(jié)構(gòu)列表開始。

成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比洋縣網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式洋縣網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋洋縣地區(qū)。費(fèi)用合理售后完善,十多年實(shí)體公司更值得信賴。

1.將兩個(gè)列表合并成一個(gè)字典

假設(shè)我們在 Python 中有兩個(gè)列表,我們希望將它們合并為字典形式,其中一個(gè)列表的項(xiàng)作為字典的鍵,另一個(gè)作為值。這是在用 Python 編寫代碼時(shí)經(jīng)常遇到的一個(gè)非常常見的問題。

但是為了解決這個(gè)問題,我們需要考慮幾個(gè)限制,比如兩個(gè)列表的大小,兩個(gè)列表中元素的類型,以及其中是否有重復(fù)的元素,尤其是我們將使用的元素作為 key 時(shí)。我們可以通過使用 zip 等內(nèi)置函數(shù)來解決這些問題。

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.將兩個(gè)或多個(gè)列表合并為一個(gè)包含列表的列表

另一個(gè)常見的任務(wù)是當(dāng)我們有兩個(gè)或更多列表時(shí),我們希望將它們?nèi)渴占揭粋€(gè)大列表中,其中較小列表的所有第一項(xiàng)構(gòu)成較大列表中的第一個(gè)列表。

例如,如果我們有 4 個(gè)列表 [1,2,3], ['a','b','c'], ['h','e','y'] 和 [4,5, 6],我們想為這四個(gè)列表創(chuàng)建一個(gè)新列表;它將是 [[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.對字典列表進(jìn)行排序

這一組日常列表任務(wù)是排序任務(wù),根據(jù)列表中包含的元素的數(shù)據(jù)類型,我們將采用稍微不同的方式對它們進(jìn)行排序。

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.對字符串列表進(jìn)行排序

我們經(jīng)常面臨包含字符串的列表,我們需要按字母順序、長度或我們想要或我們的應(yīng)用程序需要的任何其他因素對這些列表進(jìn)行排序。

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.根據(jù)另一個(gè)列表對列表進(jìn)行排序

有時(shí),我們可能需要使用一個(gè)列表來對另一個(gè)列表進(jìn)行排序,因此,我們將有一個(gè)數(shù)字列表(索引)和一個(gè)我們想使用這些索引進(jìn)行排序的列表。

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.將列表映射到字典

列表代碼片段的最后一個(gè)任務(wù),如果給定一個(gè)列表并將其映射到字典中,也就是說,我們想將我們的列表轉(zhuǎn)換為帶有數(shù)字鍵的字典。

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

現(xiàn)在處理的數(shù)據(jù)類型是字典

7.合并兩個(gè)或多個(gè)字典

假設(shè)我們有兩個(gè)或多個(gè)字典,并且我們希望將它們?nèi)亢喜橐粋€(gè)具有唯一鍵的字典。

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.反轉(zhuǎn)字典

一個(gè)非常常見的字典任務(wù)是如果我們有一個(gè)字典并且想要翻轉(zhuǎn)它的鍵和值,鍵將成為值,而值將成為鍵。

當(dāng)我們這樣做時(shí),我們需要確保沒有重復(fù)的鍵。值可以重復(fù),但鍵不能,并確保所有新鍵都是可以 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 字符串

格式化字符串可能是我們幾乎每天都需要完成的一項(xiàng)任務(wù),在 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.檢查子串

一項(xiàng)非常常見的任務(wù)就是檢查字符串是否在與字符串列表中。

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.以字節(jié)為單位獲取字符串的大小

有時(shí),尤其是在構(gòu)建內(nèi)存關(guān)鍵應(yīng)用程序時(shí),我們需要知道我們的字符串使用了多少內(nèi)存。

str1 = "hello"
str2 = ""

def str_size(s):
return len(s.encode('utf-8'))

str_size(str1)
str_size(str2)

Input/ Output operations

最后我們來看看輸入輸出方面的代碼片段

12.檢查文件是否存在

在數(shù)據(jù)科學(xué)和許多其他應(yīng)用程序中,我們經(jīng)常需要從文件中讀取數(shù)據(jù)或向其中寫入數(shù)據(jù),但要做到這一點(diǎn),我們需要檢查文件是否存在,因此,我們需要確保代碼不會因 IO 錯(cuò)誤而終止。

#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.解析電子表格

另一種非常常見的文件交互是從電子表格中解析數(shù)據(jù),我們使用 CSV 模塊來幫助我們有效地執(zhí)行該任務(wù)。

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

好了,我們一起學(xué)習(xí)了 13 個(gè)代碼片段,這些片段簡單、簡短且高效,無論我們在哪個(gè)應(yīng)用程序領(lǐng)域工作,最終都會在相應(yīng)的 Python 項(xiàng)目中至少使用其中的一個(gè),所以收藏就是最好的選擇!


當(dāng)前文章:13個(gè)非常有用的Python代碼片段,建議收藏!
分享URL:http://www.dlmjj.cn/article/cdshhod.html