Python程式設計常用的技巧有哪些?
1.字串反轉
使用Python切片反轉字串:
# Reversing a string using slicing my_string = "ABCDE" reversed_string = my_string[::-1] print(reversed_string) # Output # EDCBA
2.每個單字的第一個字母大寫
使用title函數方法:
my_string = "my name is chaitanya baweja" # using the title() function of string class new_string = my_string.title() print(new_string) # Output # My Name Is Chaitanya Baweja
3. 字串尋找唯一元素
使用集合的概念尋找字串的唯一元素:
my_string = "aavvccccddddeee" # converting the string to a set temp_set = set(my_string) # stitching set into a string using join new_string = ''.join(temp_set) print(new_string) # output # cdvae
4.重複列印字串和清單n次
你可以使用乘法符號(*)列印字串或列表多次:
n = 3 # number of repetitions my_string = "abcd" my_list = [1,2,3] print(my_string*n) # abcdabcdabcd print(my_list*n) # [1,2,3,1,2,3,1,2,3]
5.列表產生
# Multiplying each element in a list by 2 original_list = [1,2,3,4] new_list = [2*x for x in original_list] print(new_list) # [2,4,6,8]
6.變數交換
a = 1 b = 2 a, b = b, a print(a) # 2 print(b) # 1
7.字串拆分為子字串清單
使用.split()函數:
string_1 = "My name is Chaitanya Baweja" string_2 = "sample/ string 2" # default separator ' ' print(string_1.split()) # ['My', 'name', 'is', 'Chaitanya', 'Baweja'] # defining separator as '/' print(string_2.split('/')) # ['sample', ' string 2']
8.多個字串組合為一個字串
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja'] # Using join with the comma separator print(','.join(list_of_strings)) # Output # My,name,is,Chaitanya,Baweja
# 9.偵測字串是否為回文
my_string = "abcba" if my_string == my_string[::-1]: print("palindrome") else: print("not palindrome") # Output # palindrome
10.統計列表中元素的次數
# finding frequency of each element in a list from collections import Counter my_list = ['a','a','b','b','b','c','d','d','d','d','d'] count = Counter(my_list) # defining a counter object print(count) # Of all elements # Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1}) print(count['b']) # of individual element # 3 print(count.most_common(1)) # most frequent element # [('d', 5)]
11.判斷兩個字串是否為Anagrams
Anagrams的意義在兩個單字中,每個英文單字(不含大小寫)出現的次數相同,使用Counter類別判斷兩個字串是否為Anagrams。
from collections import Counter str_1, str_2, str_3 = "acbde", "abced", "abcda" cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3) if cnt_1 == cnt_2: print('1 and 2 anagram') if cnt_1 == cnt_3: print('1 and 3 anagram') # output # 1 and 2 anagram
12. 使用try-except-else-block模組
except取得例外處理:
a, b = 1,0 try: print(a/b) # exception raised when b is 0 except ZeroDivisionError: print("division by zero") else: print("no exceptions raised") finally: print("Run this always") # output # division by zero # Run this always
13. 使用枚舉函數得到key/value對
my_list = ['a', 'b', 'c', 'd', 'e'] for index, value in enumerate(my_list): print('{0}: {1}'.format(index, value)) # 0: a # 1: b # 2: c # 3: d # 4: e
14.檢查物件的記憶體使用量
import sys num = 21 print(sys.getsizeof(num)) # In Python 2, 24 # In Python 3, 28
15.合併字典
dict_1 = {'apple': 9, 'banana': 6} dict_2 = {'banana': 4, 'orange': 8} combined_dict = {**dict_1, **dict_2} print(combined_dict) # Output # {'apple': 9, 'banana': 4, 'orange': 8}
16.計算執行一段程式碼所花費的時間
使用time類別計算執行一段程式碼所花費的時間:
import time start_time = time.time() # Code to check follows for i in range(10**5): a, b = 1,2 c = a+ b # Code to check ends end_time = time.time() time_taken_in_micro = (end_time- start_time)*(10**6) print(time_taken_in_micro) # output # 18770.217895507812
17.清單展開
from iteration_utilities import deepflatten # if you only have one depth nested_list, use this def flatten(l): return [item for sublist in l for item in sublist] l = [[1,2,3],[3]] print(flatten(l)) # [1, 2, 3, 3] # if you don't know how deep the list is nested l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]] print(list(deepflatten(l, depth=3))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
18. 清單取樣
import random my_list = ['a', 'b', 'c', 'd', 'e'] num_samples = 2 samples = random.sample(my_list,num_samples) print(samples) # [ 'a', 'e'] this will have any 2 random values
19.數字化
#將整數轉換成數字清單:
num = 123456 # using map list_of_digits = list(map(int, str(num))) print(list_of_digits) # [1, 2, 3, 4, 5, 6] # using list comprehension list_of_digits = [int(x) for x in str(num)] print(list_of_digits) # [1, 2, 3, 4, 5, 6]
20.檢查清單元素的唯一性
檢查清單中每個元素是否為唯一的:
def unique(l): if len(l)==len(set(l)): print("All elements are unique") else: print("List has duplicates") unique([1,2,3,4]) # All elements are unique unique([1,1,2,3]) # List has duplicates
以上是Python程式設計常用的技巧有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

安裝pyodbc:使用pipinstallpyodbc命令安裝庫;2.連接SQLServer:通過pyodbc.connect()方法,使用包含DRIVER、SERVER、DATABASE、UID/PWD或Trusted_Connection的連接字符串,分別支持SQL身份驗證或Windows身份驗證;3.查看已安裝驅動:運行pyodbc.drivers()並篩選含'SQLServer'的驅動名,確保使用如'ODBCDriver17forSQLServer'等正確驅動名稱;4.連接字符串關鍵參數

pythoncanbeoptimizedFormized-formemory-boundoperationsbyreducingOverHeadThroughGenerator,有效dattratsures,andManagingObjectLifetimes.first,useGeneratorSInsteadoFlistSteadoflistSteadoFocessLargedAtasetSoneItematatime,desceedingingLoadeGingloadInterveringerverneDraineNterveingerverneDraineNterveInterveIntMory.second.second.second.second,Choos,Choos

shutil.rmtree()是Python中用於遞歸刪除整個目錄樹的函數,能刪除指定文件夾及其所有內容。 1.基本用法:使用shutil.rmtree(path)刪除目錄,需處理FileNotFoundError、PermissionError等異常。 2.實際應用:可一鍵清除包含子目錄和文件的文件夾,如臨時數據或緩存目錄。 3.注意事項:刪除操作不可恢復;路徑不存在時拋出FileNotFoundError;可能因權限或文件佔用導致失敗。 4.可選參數:可通過ignore_errors=True忽略錯

使用psycopg2.pool.SimpleConnectionPool可有效管理數據庫連接,避免頻繁創建和銷毀連接帶來的性能開銷。 1.創建連接池時指定最小和最大連接數及數據庫連接參數,確保連接池初始化成功;2.通過getconn()獲取連接,執行數據庫操作後使用putconn()將連接歸還池中,禁止直接調用conn.close();3.SimpleConnectionPool是線程安全的,適用於多線程環境;4.推薦結合contextmanager實現上下文管理器,確保連接在異常時也能正確歸還;

iter()用於獲取迭代器對象,next()用於獲取下一個元素;1.使用iter()可將列表等可迭代對象轉換為迭代器;2.調用next()逐個獲取元素,當元素耗盡時觸發StopIteration異常;3.通過next(iterator,default)可提供默認值避免異常;4.自定義迭代器需實現__iter__()和__next__()方法,控制迭代邏輯;使用默認值是安全遍歷的常用方式,整個機制簡潔且實用。

統計套利簡介統計套利是一種基於數學模型在金融市場中捕捉價格錯配的交易方式。其核心理念源於均值回歸,即資產價格在短期內可能偏離長期趨勢,但最終會回歸其歷史平均水平。交易者利用統計方法分析資產之間的關聯性,尋找那些通常同步變動的資產組合。當這些資產的價格關係出現異常偏離時,便產生套利機會。在加密貨幣市場,統計套利尤為盛行,主要得益於市場本身的低效率與劇烈波動。與傳統金融市場不同,加密貨幣全天候運行,價格極易受到突發新聞、社交媒體情緒及技術升級的影響。這種持續的價格波動頻繁製造出定價偏差,為套利者提供

安裝對應數據庫驅動;2.使用connect()連接數據庫;3.創建cursor對象;4.用execute()或executemany()執行SQL並用參數化查詢防注入;5.用fetchall()等獲取結果;6.修改後需commit();7.最後關閉連接或使用上下文管理器自動處理;完整流程確保安全且高效執行SQL操作。

創建Python虛擬環境可使用venv模塊,步驟為:1.進入項目目錄執行python-mvenvenv創建環境;2.Mac/Linux用sourceenv/bin/activate、Windows用env\Scripts\activate激活;3.使用pipinstall安裝包、pipfreeze>requirements.txt導出依賴;4.注意避免將虛擬環境提交到Git,並確認安裝時處於正確環境。虛擬環境能隔離項目依賴防止衝突,尤其適合多項目開發,編輯器如PyCharm或VSCode也
