Fatos Morina Crossin的編程教室 2月16日python
原文:30 Helpful Python Snippets That You Can Learn in 30 Seconds or Lesshttps://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172做者:Fatos Morina(https://towardsdatascience.com/@FatosMorina)web
翻譯:Pita & AI開發者編程
你們好,歡迎來到 Crossin的編程教室 !app
Python是目前最流行的語言之一,它在數據科學、機器學習、web開發、腳本編寫、自動化方面被許多人普遍使用。它的簡單和易用性造就了它如此流行的緣由。less
在本文中,咱們將會介紹 30 個簡短的代碼片斷,你能夠在 30 秒或更短的時間裏理解和學習這些代碼片斷。機器學習
1.檢查重複元素
ide
下面的方法能夠檢查給定列表中是否有重複的元素。它使用了 set() 屬性,該屬性將會從列表中刪除重複的元素。學習
def all_unique(lst): return len(lst) == len(set(lst)) x = [1,1,2,2,3,2,3,4,5,6] y = [1,2,3,4,5] all_unique(x) # False all_unique(y) # True
2.變位詞
ui
檢測兩個字符串是否互爲變位詞(即互相顛倒字符順序)spa
from collections import Counter def anagram(first, second): return Counter(first) == Counter(second) anagram("abcd3", "3acdb") # True
3.檢查內存使用狀況
如下代碼段可用來檢查對象的內存使用狀況。
import sys variable = 30 print(sys.getsizeof(variable)) # 24
4.字節大小計算
如下方法將以字節爲單位返回字符串長度。
def byte_size(string): return(len(string.encode('utf-8'))) byte_size('