首頁  >  文章  >  後端開發  >  Python程式設計必備的12個必備程式碼片段

Python程式設計必備的12個必備程式碼片段

WBOY
WBOY轉載
2023-04-26 15:52:081726瀏覽

12 个用于日常编程的杀手级 Python 代码片段

1、正規表示式

正規表示式是 Python 中匹配模式、搜尋和取代字串、驗證字串等的最佳技術。現在,您無需為此類工作使用循環和清單。

查看以下關於驗證電子郵件格式的正規表示式片段程式碼範例:

# Regular Expression Check Mail
import re
def Check_Mail(email):
 pattern = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(.[A-Z|a-z]{2,})+')
 if re.fullmatch(pattern, email):
 print("valid")
 else:
 print("Invalid")
Check_Mail("codedev101@gmail.com") #valid
Check_Mail("codedev101-haider@uni.edu")#Invalid
Check_Mail("code-101-work@my.net") # Invalid

2、Pro Slicing

這個簡單的程式碼片段將幫助您像專業人士一樣對清單進行切片。請參閱下面的範例程式碼:

# Pro Slicing
# list[start:end:step]
mylist = [1, 2, 3, 5, 5, 6, 7, 8, 9, 12]
mail ="codedev-medium@example.com"
print(mylist[4:-3]) # 5 6 7
print(mail[8 : 14]) # medium

3、Swap without Temp

#您是否使用 Temp 變數來交換兩個數據,而不是在 Python 中您不需要使用它?在此程式碼片段中,我將與您分享如何在不使用 temp 的情況下交換兩個資料變數。

看下面的程式碼:

# Swap without Temp
i = 134
j = 431
[i, j] = [j, i]
print(i) #431
print(j) #134

4、Magic of F-string

我們可能使用format() 方法或「%」方法來格式化字串中的變數。這段程式碼將向您介紹 F 字串,它比另一種格式要好得多。

看看下面的範例程式碼:

# Magic of f-String
# Normal Method
name = "Codedev"
lang = "Python"
data = "{} is writing article on {}".format(name, lang)
print(data)
# Pro Method with f-string
data = f"{name} is writing article on {lang}"
print(data

5、取得索引

現在您不再需要 Loop 來尋找特定元素的索引。您可以使用清單中的 index() 方法來完成。

查看下面的程式碼:

# Get Index
x = [10 ,20, 30, 40, 50]
print(x.index(10)) # 0
print(x.index(30)) # 4
print(x.index(50)) # 2

6、基於Another List的排序清單

此程式碼片段將向您展示如何根據另一個列表對清單進行排序。當您需要根據所需的位置進行排序時,此程式碼片段非常方便。

# Sort List based on another List
list1 =["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]
list2 = [ 0, 1, 1, 1, 2, 2, 0, 1, 1, 3, 4]
C = [x for _, x in sorted(zip(list2, list1), key=lambda pair: pair[0])]
print(C) # ['a', 'g', 'b', 'c', 'd', 'h', 'i', 'e', 'f', 'j', 'k']

7、 反轉字典

現在您不需要循環來反轉任何字典。此程式碼段程式碼將在第二次嘗試該程式碼段程式碼時反轉字典。

# Invert the Dictionary
def Invert_Dictionary(data):
 return{value: key for key, value in data.items()}
data = {"A": 1, "B":2, "C": 3}
invert = Invert_Dictionary(data)
print(invert) # {1: 'A', 2: 'B', 3: 'C'}

8、多執行緒

多執行緒將幫助您同時並行運行 Python 函數。假設您想同時執行 5 個函數,而無需等待每個函數完成。

查看下面的程式碼片段:

# Multi-threading
import threading
def func(num):
 for x in range(num):
 print(x)
if __name__ == "__main__":
 t1 = threading.Thread(target=func, args=(10,))
 t2 = threading.Thread(target=func, args=(20,))
 t1.start()
 t2.start()
 t1.join()
 t2.join()

9、清單中出現最多的元素

此片段程式碼將簡單地計算清單中出現次數最多的元素。我已經展示了兩種方法來做到這一點。

在下面查看它:

# Element Occur most in List
from collections import Counter
mylst = ["a", "a", "b", "c", "a", "b","b", "c", "d", "a"]
# Method 1
def occur_most1(mylst):
 return max(set(mylst), key=mylst.count)
print(occur_most1(mylst)) # a
# Method 2
# Much Faster then Method 1
def occur_most2(mylst):
 data = Counter(mylst)
 return data.most_common(1)[0][0]
print(occur_most2(mylst)) # a

10、分割線

有一個逐行格式的原始文本,並希望將其分成幾行。此程式碼段將在一秒鐘內解決您的問題。

# Split lines
data1 = """Hello to
Python"""
data2 = """Programming
Langauges"""
print(data1.split("n")) # ['Hello to', 'Python']
print(data2.split("n")) # ['Programming', ' Langauges']

11、 將清單對應到字典

此程式碼片段將幫助您將任意兩個清單轉換為字典格式。要了解它是如何運作的,請查看下面的程式碼:

# Map List into Dictionary
def Convert_to_Dict(k, v):
 return dict(zip(k, v))
k = ["a", "b", "c", "d", "e"]
v = [1, 2, 3, 4, 5]
print(Convert_to_Dict(k, v)) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

12、解析電子表格

現在您不需要Pandas 或任何其他外部Python 套件來解析電子表格。 Python 有一個內建的 CSV 模組,這段程式碼將向您展示如何使用它。

# Parse Spreadsheet
import csv
#Reading
with open("test.csv", "r") as file:
 csv_reader = csv.reader(file)
 for row in csv_reader:
 print(row)
file.close()
#Writing
header = ["ID", "Languages"]
csv_data = [234, "Python", 344, "JavaScript", 567, "Dart"]
with open("test2.csv", 'w', newline="") as file:
 csv_writer = csv.writer(file)
 csv_writer.writerow(header)
 csv_writer.writerows(csv_data)

以上是Python程式設計必備的12個必備程式碼片段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除