1. 程式人生 > 實用技巧 >python dumps 詳解,困擾你的is not JSON serializable

python dumps 詳解,困擾你的is not JSON serializable

許多人在資料科學、機器學習、web開發、指令碼編寫和自動化等領域中都會使用Python,它是一種十分流行的語言。

Python流行的部分原因在於簡單易學。

本文將簡要介紹30個簡短的、且能在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. 記憶體

此程式碼段可用於檢查物件的記憶體使用情況。

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 = 2; 
s ="Programming"; 
print(s * n); # ProgrammingProgramming

6. 首字母大寫

以下程式碼片段只利用了title(),就能將字串中每個單詞的首字母大寫。

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

7. 列表細分

該方法將列表細分為特定大小的列表。

def chunk(list, size):
   return [list[i:i+size] for i in range(0,len(list), size)]

8. 壓縮

以下程式碼使用filter()從,將錯誤值(False、None、0和“ ”)從列表中刪除。

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

9. 計數

以下程式碼可用於調換2D陣列排列。

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. 尋找差異

此方法僅保留第一個迭代中的值來查詢兩個迭代之間的差異

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. 重複值存在與否

以下方法利用set()只包含唯一元素的特性來檢查列表是否存在重複值。

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}

在Python3.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. 列舉

以下程式碼段可以採用列舉的方式來獲取列表的值和索引。

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語句

可將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語句的計算器

以下程式碼片段展示瞭如何在不用if-else條件語句的情況下,編寫簡易計算器。

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

27. 隨機排序

該演算法採用Fisher-Yates algorithm對新列表中的元素進行隨機排序。

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. 展開列表

此方法將類似javascript中[].concat(…arr)這樣的列表展開。

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)


30. 獲取丟失部分的預設值

以下程式碼可在所需物件不在字型檔範圍內的情況下獲取預設值。

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

本文只簡單介紹了一些能在日常工作中幫到我們的方法。但內容都主要立足於GitHub 儲存庫:https://github.com/30-seconds/30_seconds_of_knowledge,該儲存庫還包含了有關Python及其他語言和技術行之有效的程式碼。