30段極簡Python代碼:這些小技巧你都Get了么

  • 2019 年 10 月 7 日
  • 筆記

選自towardsdatascience

作者:Fatos Morina

機器之心編譯

參與:思源

學 Python 怎樣才最快,當然是實戰各種小項目,只有自己去想與寫,才記得住規則。本文是 30 個極簡任務,初學者可以嘗試着自己實現;本文同樣也是 30 段代碼,Python 開發者也可以看看是不是有沒想到的用法。

Python 是機器學習最廣泛採用的編程語言,它最重要的優勢在於編程的易用性。如果讀者對基本的 Python 語法已經有一些了解,那麼這篇文章可能會給你一些啟發。作者簡單概覽了 30 段代碼,它們都是平常非常實用的技巧,我們只要花幾分鐘就能從頭到尾瀏覽一遍。

1. 重複元素判定

以下方法可以檢查給定列表是不是存在重複元素,它會使用 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. 字符元素組成判定

檢查兩個字符串的組成元素是不是一樣的。

from collections import Counter    def anagram(first, second):      return Counter(first) == Counter(second)      anagram("abcd3", "3acdb") # True

3. 內存佔用

下面的代碼塊可以檢查變量 variable 所佔用的內存。

import sys    variable = 30  print(sys.getsizeof(variable)) # 24

4. 位元組佔用

下面的代碼塊可以檢查字符串佔用的位元組數。

def byte_size(string):      return(len(string.encode('utf-8')))      byte_size('?') # 4  byte_size('Hello World') # 11   

5. 打印 N 次字符串

該代碼塊不需要循環語句就能打印 N 次字符串。

n = 2;  s ="Programming";    print(s * n);  # ProgrammingProgramming  

6. 大寫第一個字母

以下代碼塊會使用 title() 方法,從而大寫字符串中每一個單詞的首字母。

s = "programming is awesome"    print(s.title())  # Programming Is Awesome

7. 分塊

給定具體的大小,定義一個函數以按照這個大小切割列表。

from math import ceil    def chunk(lst, size):      return list(          map(lambda x: lst[x * size:x * size + size],              list(range(0, ceil(len(lst) / size)))))        chunk([1,2,3,4,5],2)  # [[1,2],[3,4],5]

8. 壓縮

這個方法可以將布爾型的值去掉,例如(False,None,0,「」),它使用 filter() 函數。

def compact(lst):      return list(filter(bool, lst))      compact([0, 1, False, 2, '', 3, 'a', 's', 34])  # [ 1, 2, 3, 'a', 's', 34 ]

9. 解包

如下代碼段可以將打包好的成對列表解開成兩組不同的元組。

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]  transposed = zip(*array)  print(transposed)  # [('a', 'c', 'e'), ('b', 'd', 'f')]

10. 鏈式對比

我們可以在一行代碼中使用不同的運算符對比多個不同的元素。

a = 3  print( 2 < a < 8) # True  print(1 == a < 2) # False

11. 逗號連接

下面的代碼可以將列表連接成單個字符串,且每一個元素間的分隔方式設置為了逗號。

hobbies = ["basketball", "football", "swimming"]    print("My hobbies are: " + ", ".join(hobbies))  # My hobbies are: basketball, football, swimming

12. 元音統計

以下方法將統計字符串中的元音 (『a』, 『e』, 『i』, 『o』, 『u』) 的個數,它是通過正則表達式做的。

import re    def count_vowels(str):      return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))    count_vowels('foobar') # 3  count_vowels('gym') # 0

13. 首字母小寫

如下方法將令給定字符串的第一個字符統一為小寫。

def decapitalize(string):      return str[:1].lower() + str[1:]      decapitalize('FooBar') # 'fooBar'  decapitalize('FooBar') # 'fooBar'

14. 展開列表

該方法將通過遞歸的方式將列表的嵌套展開為單個列表。

def spread(arg):      ret = []      for i in arg:          if isinstance(i, list):              ret.extend(i)          else:              ret.append(i)      return ret    def deep_flatten(lst):      result = []      result.extend(          spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))      return result      deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

15. 列表的差

該方法將返回第一個列表的元素,其不在第二個列表內。如果同時要反饋第二個列表獨有的元素,還需要加一句 set_b.difference(set_a)。

def difference(a, b):      set_a = set(a)      set_b = set(b)      comparison = set_a.difference(set_b)      return list(comparison)      difference([1,2,3], [1,2,4]) # [3]

16. 通過函數取差

如下方法首先會應用一個給定的函數,然後再返回應用函數後結果有差別的列表元素。

def difference_by(a, b, fn):      b = set(map(fn, b))      return [item for item in a if fn(item) not in b]      from math import floor  difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]  difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])  # [ { x: 2 } ]

17. 鏈式函數調用

你可以在一行代碼內調用多個函數。

def add(a, b):      return a + b    def subtract(a, b):      return a - b    a, b = 4, 5  print((subtract if a > b else add)(a, b)) # 9 

18. 檢查重複項

如下代碼將檢查兩個列表是不是有重複項。

def has_duplicates(lst):      return len(lst) != len(set(lst))      x = [1,2,3,4,5,5]  y = [1,2,3,4,5]  has_duplicates(x) # True  has_duplicates(y) # False

19. 合併兩個字典

下面的方法將用於合併兩個字典。

def merge_two_dicts(a, b):      c = a.copy()   # make a copy of a      c.update(b)    # modify keys and values of a with the ones from b      return c      a = { 'x': 1, 'y': 2}  b = { 'y': 3, 'z': 4}  print(merge_two_dicts(a, b))  # {'y': 3, 'x': 1, 'z': 4}

在 Python 3.5 或更高版本中,我們也可以用以下方式合併字典:

def merge_dictionaries(a, b)     return {**a, **b}      a = { 'x': 1, 'y': 2}  b = { 'y': 3, 'z': 4}  print(merge_dictionaries(a, b))  # {'y': 3, 'x': 1, 'z': 4}

20. 將兩個列錶轉化為字典

如下方法將會把兩個列錶轉化為單個字典。

def to_dictionary(keys, values):      return dict(zip(keys, values))      keys = ["a", "b", "c"]  values = [2, 3, 4]  print(to_dictionary(keys, values))  # {'a': 2, 'c': 4, 'b': 3}

21. 使用枚舉

我們常用 For 循環來遍歷某個列表,同樣我們也能枚舉列表的索引與值。

list = ["a", "b", "c", "d"]  for index, element in enumerate(list):      print("Value", element, "Index ", index, )    # ('Value', 'a', 'Index ', 0)  # ('Value', 'b', 'Index ', 1)  #('Value', 'c', 'Index ', 2)  # ('Value', 'd', 'Index ', 3)    

22. 執行時間

如下代碼塊可以用來計算執行特定代碼所花費的時間。

import time    start_time = time.time()    a = 1  b = 2  c = a + b  print(c) #3    end_time = time.time()  total_time = end_time - start_time  print("Time: ", total_time)    # ('Time: ', 1.1205673217773438e-05)  

23.Try else

我們在使用 try/except 語句的時候也可以加一個 else 子句,如果沒有觸發錯誤的話,這個子句就會被運行。

try:      2*3  except TypeError:      print("An exception was raised")  else:      print("Thank God, no exceptions were raised.")    #Thank God, no exceptions were raised.

24. 元素頻率

下面的方法會根據元素頻率取列表中最常見的元素。

def most_frequent(list):      return max(set(list), key = list.count)      list = [1,2,1,2,3,2,1,4,2]  most_frequent(list)  

25. 迴文序列

以下方法會檢查給定的字符串是不是迴文序列,它首先會把所有字母轉化為小寫,並移除非英文字母符號。最後,它會對比字符串與反向字符串是否相等,相等則表示為迴文序列。

def palindrome(string):      from re import sub      s = sub('[W_]', '', string.lower())      return s == s[::-1]      palindrome('taco cat') # True

26. 不使用 if-else 的計算子

這一段代碼可以不使用條件語句就實現加減乘除、求冪操作,它通過字典這一數據結構實現:

import operator  action = {      "+": operator.add,      "-": operator.sub,      "/": operator.truediv,      "*": operator.mul,      "**": pow  }  print(action['-'](50, 25)) # 25

27.Shuffle

該算法會打亂列表元素的順序,它主要會通過 Fisher-Yates 算法對新列表進行排序:

from copy import deepcopy  from random import randint    def shuffle(lst):      temp_lst = deepcopy(lst)      m = len(temp_lst)      while (m):          m -= 1          i = randint(0, m)          temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]      return temp_lst      foo = [1,2,3]  shuffle(foo) # [2,3,1] , foo = [1,2,3]

28. 展開列表

將列表內的所有元素,包括子列表,都展開成一個列表。

def spread(arg):      ret = []      for i in arg:          if isinstance(i, list):              ret.extend(i)          else:              ret.append(i)      return ret      spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

29. 交換值

不需要額外的操作就能交換兩個變量的值。

def swap(a, b):    return b, a    a, b = -1, 14  swap(a, b) # (14, -1)  spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

30. 字典默認值

通過 Key 取對應的 Value 值,可以通過以下方式設置默認值。如果 get() 方法沒有設置默認值,那麼如果遇到不存在的 Key,則會返回 None。

d = {'a': 1, 'b': 2}    print(d.get('c', 3)) # 3  

參考鏈接:https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

本文為機器之心編譯,轉載請聯繫本公眾號獲得授權。