自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

13 個非常有用的 Python 代碼片段,建議收藏!

開發(fā) 前端
今天我們主要來介紹應(yīng)用程序當中的通用 Python 代碼片段,一起進步吧。

?今天我們主要來介紹應(yīng)用程序當中的通用 Python 代碼片段,一起進步吧。

Lists Snippets

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

1.將兩個列表合并成一個字典

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

但是為了解決這個問題,我們需要考慮幾個限制,比如兩個列表的大小,兩個列表中元素的類型,以及其中是否有重復(fù)的元素,尤其是我們將使用的元素作為 key 時。我們可以通過使用 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.將兩個或多個列表合并為一個包含列表的列表

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

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

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

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īng)常面臨包含字符串的列表,我們需要按字母順序、長度或我們想要或我們的應(yīng)用程序需要的任何其他因素對這些列表進行排序。

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ù)另一個列表對列表進行排序

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

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

列表代碼片段的最后一個任務(wù),如果給定一個列表并將其映射到字典中,也就是說,我們想將我們的列表轉(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.合并兩個或多個字典

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

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)字典

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

當我們這樣做時,我們需要確保沒有重復(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 字符串

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

一項非常常見的任務(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é)為單位獲取字符串的大小

有時,尤其是在構(gòu)建內(nèi)存關(guān)鍵應(yīng)用程序時,我們需要知道我們的字符串使用了多少內(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ù)科學和許多其他應(yīng)用程序中,我們經(jīng)常需要從文件中讀取數(shù)據(jù)或向其中寫入數(shù)據(jù),但要做到這一點,我們需要檢查文件是否存在,因此,我們需要確保代碼不會因 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.解析電子表格

另一種非常常見的文件交互是從電子表格中解析數(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

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

責任編輯:華軒 來源: 蘿卜大雜燴
相關(guān)推薦

2023-06-13 15:15:02

JavaScript前端編程語言

2017-08-02 13:32:18

編程Java程序片段

2013-06-14 14:57:09

Java基礎(chǔ)代碼

2020-10-29 10:00:55

Python函數(shù)文件

2022-09-02 23:08:04

JavaScript技巧開發(fā)

2011-07-07 17:16:43

PHP

2023-02-19 15:22:22

React技巧

2009-03-24 14:23:59

PHP類庫PHP開發(fā)PHP

2022-07-20 09:05:06

Python編程語言

2025-02-13 08:06:54

2009-05-18 16:58:56

Java代碼片段

2017-11-16 08:15:26

程序員Java程序

2025-02-26 11:05:03

2018-08-03 10:02:05

Linux命令

2013-11-05 10:03:22

Eclipse功能

2021-10-30 18:59:15

Python

2013-08-21 10:31:22

HTML5工具

2013-08-12 15:00:24

LinuxLinux命令

2021-03-09 09:14:27

ES2019JavaScript開發(fā)

2009-02-09 11:20:06

Windows7Windows
點贊
收藏

51CTO技術(shù)棧公眾號