程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

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

編輯:Python

作者 | 周蘿蔔

來源 | 蘿蔔大雜燴

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

Lists Snippets

我們先從最常用的數據結構列錶開始

№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 = ""
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 = 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 項目中至少使用其中的一個,所以收藏就是最好的選擇!

往期回顧

NLP 類問題建模方案探索實踐

Python 爬蟲中的常見加密算法!

2D變身3D,來看英偉達的AI“新”魔法!

搞定Python幾個常用的數據結構!

分享
點收藏
點點贊
點在看

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved