12 個用于日常編程的殺手級 Python 代碼片段
1、正則表達式
正則表達式是 Python 中匹配模式、搜索和替換字符串、驗證字符串等的最佳技術(shù)?,F(xiàn)在,您無需為此類工作使用循環(huán)和列表。
查看以下關(guān)于驗證電子郵件格式的正則表達式片段代碼示例:
# 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
這個簡單的代碼片段將幫助您像專業(yè)人士一樣對列表進行切片。查看下面的示例代碼:
# 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 變量來交換兩個數(shù)據(jù),而不是在 Python 中您不需要使用它?在此代碼段中,我將與您分享如何在不使用 temp 的情況下交換兩個數(shù)據(jù)變量。
查看下面的代碼:
# 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、獲取索引
現(xiàn)在您不再需要 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的排序列表
此代碼段將向您展示如何根據(jù)另一個列表對列表進行排序。當(dāng)您需要根據(jù)所需的位置進行排序時,此代碼段非常方便。
# 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、 反轉(zhuǎn)字典
現(xiàn)在您不需要循環(huán)來反轉(zhuǎn)任何字典。此代碼段代碼將在第二次嘗試該代碼段代碼時反轉(zhuǎn)字典。
# 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 函數(shù)。假設(shè)您想同時執(zhí)行 5 個函數(shù),而無需等待每個函數(shù)完成。
查看下面的代碼段:
# 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、列表中出現(xiàn)最多的元素
此片段代碼將簡單地計算列表中出現(xiàn)次數(shù)最多的元素。我已經(jīng)展示了兩種方法來做到這一點。
在下面查看它:
# 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、分割線
有一個逐行格式的原始文本,并希望將其分成幾行。此代碼段將在一秒鐘內(nèi)解決您的問題。
# Split lines
data1 = """Hello to
Python"""
data2 = """Programming
Langauges"""
print(data1.split("\n")) # ['Hello to', 'Python']
print(data2.split("\n")) # ['Programming', ' Langauges']
11、 將列表映射到字典
此代碼段將幫助您將任意兩個列表轉(zhuǎn)換為字典格式。要了解它是如何工作的,請查看下面的代碼:
# 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、解析電子表格
現(xiàn)在您不需要 Pandas 或任何其他外部 Python 包來解析電子表格。Python 有一個內(nèi)置的 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)