60 個 Python 闖關小例子,建議收藏!

2021-12-23 數據分析1480

一、 數字

1 求絕對值

絕對值或複數的模

In [1]: abs(-6)
Out[1]: 6

2 進位轉化

十進位轉換為二進位:

In [2]: bin(10)
Out[2]: '0b1010'

十進位轉換為八進位:

In [3]: oct(9)
Out[3]: '0o11'

十進位轉換為十六進位:

In [4]: hex(15)
Out[4]: '0xf'

3 整數和ASCII互轉

十進位整數對應的ASCII字符

In [1]: chr(65)
Out[1]: 'A'

查看某個ASCII字符對應的十進位數

In [1]: ord('A')
Out[1]: 65

4 元素都為真檢查

所有元素都為真,返回 True,否則為False

In [5]: all([1,0,3,6])
Out[5]: False

In [6]: all([1,2,3])
Out[6]: True

5 元素至少一個為真檢查 

至少有一個元素為真返回True,否則False

In [7]: any([0,0,0,[]])
Out[7]: False

In [8]: any([0,0,1])
Out[8]: True

6 判斷是真是假  

測試一個對象是True, 還是False.

In [9]: bool([0,0,0])
Out[9]: True

In [10]: bool([])
Out[10]: False

In [11]: bool([1,0,1])
Out[11]: True

7 創建複數

創建一個複數

In [1]: complex(1,2)
Out[1]: (1+2j)

8 取商和餘數  

分別取商和餘數

In [1]: divmod(10,3)
Out[1]: (3, 1)

9 轉為浮點類型 

將一個整數或數值型字符串轉換為浮點數

In [1]: float(3)
Out[1]: 3.0

如果不能轉化為浮點數,則會報ValueError:

In [2]: float('a')
# ValueError: could not convert string to float: 'a'

10 轉為整型  

int(x, base =10) , x可能為字符串或數值,將x 轉換為一個普通整數。如果參數是字符串,那麼它可能包含符號和小數點。如果超出了普通整數的表示範圍,一個長整數被返回。

In [1]: int('12',16)
Out[1]: 18

11 次冪

base為底的exp次冪,如果mod給出,取餘

In [1]: pow(3, 2, 4)
Out[1]: 1

12 四捨五入

四捨五入,ndigits代表小數點後保留幾位:

In [11]: round(10.0222222, 3)
Out[11]: 10.022

In [12]: round(10.05,1)
Out[12]: 10.1

13 鏈式比較

i = 3
print(1 < i < 3) # False
print(1 < i <= 3) # True

二、 字符串14 字符串轉字節  

字符串轉換為字節類型

In [12]: s = "apple"

In [13]: bytes(s,encoding='utf-8')
Out[13]: b'apple'

15 任意對象轉為字符串  

In [14]: i = 100

In [15]: str(i)
Out[15]: '100'

In [16]: str([])
Out[16]: '[]'

In [17]: str(tuple())
Out[17]: '()'

16 執行字符串表示的代碼

將字符串編譯成python能識別或可執行的代碼,也可以將文字讀成字符串再編譯。

In [1]: s = "print('helloworld')"

In [2]: r = compile(s,"<string>", "exec")

In [3]: r
Out[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>

In [4]: exec(r)
helloworld

17 計算表達式

將字符串str 當成有效的表達式來求值並返回計算結果取出字符串中內容

In [1]: s = "1 + 3 +5"
...: eval(s)
...:
Out[1]: 9

18 字符串格式化 

格式化輸出字符串,format(value, format_spec)實質上是調用了value的__format__(format_spec)方法。

In [104]: print("i am {0},age{1}".format("tom",18))
i am tom,age18

3.1415926{:.2f}3.14保留小數點後兩位3.1415926{:+.2f}+3.14帶符號保留小數點後兩位-1{:+.2f}-1.00帶符號保留小數點後兩位2.71828{:.0f}3不帶小數5{:0>2d}05數字補零 (填充左邊, 寬度為2)5{:x<4d}5xxx數字補x (填充右邊, 寬度為4)10{:x<4d}10xx數字補x (填充右邊, 寬度為4)1000000{:,}1,000,000以逗號分隔的數字格式0.25{:.2%}25.00%百分比格式1000000000{:.2e}1.00e+09指數記法18{:>10d}' 18'右對齊 (默認, 寬度為10)18{:<10d}'18 '左對齊 (寬度為10)18{:^10d}' 18 '中間對齊 (寬度為10)

三、 函數

19 拿來就用的排序函數

排序:

In [1]: a = [1,4,2,3,1]

In [2]: sorted(a,reverse=True)
Out[2]: [4, 3, 2, 1, 1]

In [3]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'
...: xiaohong','age':20,'gender':'female'}]
In [4]: sorted(a,key=lambda x: x['age'],reverse=False)
Out[4]:
[{'name': 'xiaoming', 'age': 18, 'gender': 'male'},
{'name': 'xiaohong', 'age': 20, 'gender': 'female'}]

20 求和函數

求和:

In [181]: a = [1,4,2,3,1]

In [182]: sum(a)
Out[182]: 11

In [185]: sum(a,10) #求和的初始值為10
Out[185]: 21

21 nonlocal用於內嵌函數中

關鍵詞nonlocal常用於函數嵌套中,聲明變量i為非局部變量;如果不聲明,i+=1表明i為函數wrapper內的局部變量,因為在i+=1引用(reference)時,i未被聲明,所以會報unreferenced variable的錯誤。

def excepter(f):
i = 0
t1 = time.time()
def wrapper():
try:
f()
except Exception as e:
nonlocal i
i += 1
print(f'{e.args[0]}: {i}')
t2 = time.time()
if i == n:
print(f'spending time:{round(t2-t1,2)}')
return wrapper

22 global 聲明全局變量

先回答為什麼要有global,一個變量被多個函數引用,想讓全局變量被所有函數共享。有的夥伴可能會想這還不簡單,這樣寫:

i = 5
def f():
print(i)

def g():
print(i)
pass

f()
g()

f和g兩個函數都能共享變量i,程序沒有報錯,所以他們依然不明白為什麼要用global.

但是,如果我想要有個函數對i遞增,這樣:

def h():
i += 1

h()

此時執行程序,bang, 出錯了!拋出異常:UnboundLocalError,原來編譯器在解釋i+=1時會把i解析為函數h()內的局部變量,很顯然在此函數內,編譯器找不到對變量i的定義,所以會報錯。

global就是為解決此問題而被提出,在函數h內,顯式地告訴編譯器i為全局變量,然後編譯器會在函數外面尋找i的定義,執行完i+=1後,i還為全局變量,值加1:

i = 0
def h():
global i
i += 1

h()
print(i)

23 交換兩元素

def swap(a, b):
return b, a


print(swap(1, 0)) # (0,1)

24 操作函數對象

In [31]: def f():
...: print('i\'m f')
...:

In [32]: def g():
...: print('i\'m g')
...:

In [33]: [f,g][1]()
i'm g

創建函數對象的list,根據想要調用的index,方便統一調用。

25 生成逆序序列

list(range(10,-1,-1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

第三個參數為負時,表示從第一個參數開始遞減,終止到第二個參數(不包括此邊界)

26 函數的五類參數使用例子

python五類參數:位置參數,關鍵字參數,默認參數,可變位置或關鍵字參數的使用。

def f(a,*b,c=10,**d):
print(f'a:{a},b:{b},c:{c},d:{d}')

默認參數c不能位於可變關鍵字參數d後.

調用f:

In [10]: f(1,2,5,width=10,height=20)
a:1,b:(2, 5),c:10,d:{'width': 10, 'height': 20}

可變位置參數b實參後被解析為元組(2,5);而c取得默認值10; d被解析為字典.

再次調用f:

In [11]: f(a=1,c=12)
a:1,b:(),c:12,d:{}

a=1傳入時a就是關鍵字參數,b,d都未傳值,c被傳入12,而非默認值。

注意觀察參數a, 既可以f(1),也可以f(a=1) 其可讀性比第一種更好,建議使用f(a=1)。如果要強制使用f(a=1),需要在前面添加一個星號:

def f(*,a,**b):
print(f'a:{a},b:{b}')

此時f(1)調用,將會報錯:TypeError: f() takes 0 positional arguments but 1 was given

只能f(a=1)才能OK.

說明前面的*發揮作用,它變為只能傳入關鍵字參數,那麼如何查看這個參數的類型呢?藉助python的inspect模塊:

In [22]: for name,val in signature(f).parameters.items():
...: print(name,val.kind)
...:
a KEYWORD_ONLY
b VAR_KEYWORD

可看到參數a的類型為KEYWORD_ONLY,也就是僅僅為關鍵字參數。

但是,如果f定義為:

def f(a,*b):
print(f'a:{a},b:{b}')

查看參數類型:

In [24]: for name,val in signature(f).parameters.items():
...: print(name,val.kind)
...:
a POSITIONAL_OR_KEYWORD
b VAR_POSITIONAL

可以看到參數a既可以是位置參數也可是關鍵字參數。

27 使用slice對象

生成關於蛋糕的序列cake1:

In [1]: cake1 = list(range(5,0,-1))

In [2]: b = cake1[1:10:2]

In [3]: b
Out[3]: [4, 2]

In [4]: cake1
Out[4]: [5, 4, 3, 2, 1]

再生成一個序列:

In [5]: from random import randint
...: cake2 = [randint(1,100) for _ in range(100)]
...: # 同樣以間隔為2切前10個元素,得到切片d
...: d = cake2[1:10:2]
In [6]: d
Out[6]: [75, 33, 63, 93, 15]

你看,我們使用同一種切法,分別切開兩個蛋糕cake1,cake2. 後來發現這種切法極為經典,又拿它去切更多的容器對象。

那麼,為什麼不把這種切法封裝為一個對象呢?於是就有了slice對象。

定義slice對象極為簡單,如把上面的切法定義成slice對象:

perfect_cake_slice_way = slice(1,10,2)
#去切cake1
cake1_slice = cake1[perfect_cake_slice_way]
cake2_slice = cake2[perfect_cake_slice_way]

In [11]: cake1_slice
Out[11]: [4, 2]

In [12]: cake2_slice
Out[12]: [75, 33, 63, 93, 15]

與上面的結果一致。

對於逆向序列切片,slice對象一樣可行:

a = [1,3,5,7,9,0,3,5,7]
a_ = a[5:1:-1]

named_slice = slice(5,1,-1)
a_slice = a[named_slice]

In [14]: a_
Out[14]: [0, 9, 7, 5]

In [15]: a_slice
Out[15]: [0, 9, 7, 5]

頻繁使用同一切片的操作可使用slice對象抽出來,復用的同時還能提高代碼可讀性。

28 lambda 函數的動畫演示

有些讀者反映,lambda函數不太會用,問我能不能解釋一下。

比如,下面求這個 lambda函數:

def max_len(*lists):
return max(*lists, key=lambda v: len(v))

有兩點疑惑:

調用上面函數,求出以下三個最長的列表:

r = max_len([1, 2, 3], [4, 5, 6, 7], [8])
print(f'更長的列表是{r}')

結論:

四、 數據結構29 轉為字典  

創建數據字典

In [1]: dict()
Out[1]: {}

In [2]: dict(a='a',b='b')
Out[2]: {'a': 'a', 'b': 'b'}

In [3]: dict(zip(['a','b'],[1,2]))
Out[3]: {'a': 1, 'b': 2}

In [4]: dict([('a',1),('b',2)])
Out[4]: {'a': 1, 'b': 2}

30 凍結集合  

創建一個不可修改的集合。

In [1]: frozenset([1,1,3,2,3])
Out[1]: frozenset({1, 2, 3})

因為不可修改,所以沒有像set那樣的add和pop方法

31 轉為集合類型

返回一個set對象,集合內不允許有重複元素:

In [159]: a = [1,4,2,3,1]

In [160]: set(a)
Out[160]: {1, 2, 3, 4}

32 轉為切片對象

class slice(start, stop[, step])

返回一個表示由 range(start, stop, step) 所指定索引集的 slice對象,它讓代碼可讀性、可維護性變好。

In [1]: a = [1,4,2,3,1]

In [2]: my_slice_meaning = slice(0,5,2)

In [3]: a[my_slice_meaning]
Out[3]: [1, 2, 1]

33 轉元組

tuple() 將對象轉為一個不可變的序列類型

In [16]: i_am_list = [1,3,5]
In [17]: i_am_tuple = tuple(i_am_list)
In [18]: i_am_tuple

Out[18]: (1, 3, 5)

五、 類和對象34 是否可調用  

檢查對象是否可被調用

In [1]: callable(str)
Out[1]: True

In [2]: callable(int)
Out[2]: True

In [18]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...

In [19]: xiaoming = Student('001','xiaoming')

In [20]: callable(xiaoming)
Out[20]: False

如果能調用xiaoming(), 需要重寫Student類的__call__方法:

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: def __call__(self):
...: print('I can be called')
...: print(f'my name is {self.name}')
...:

In [2]: t = Student('001','xiaoming')

In [3]: t()
I can be called
my name is xiaoming

35 ascii 展示對象  

調用對象的 __repr__ 方法,獲得該方法的返回值,如下例子返回值為字符串

>>> class Student():
def __init__(self,id,name):
self.id = id
self.name = name
def __repr__(self):
return 'id = '+self.id +', name = '+self.name

調用:

>>> xiaoming = Student(id='1',name='xiaoming')
>>> xiaoming
id = 1, name = xiaoming
>>> ascii(xiaoming)
'id = 1, name = xiaoming'

36 類方法 

classmethod 裝飾器對應的函數不需要實例化,不需要 self 參數,但第一個參數需要是表示自身類的 cls 參數,可以來調用類的屬性,類的方法,實例化對象等。

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: @classmethod
...: def f(cls):
...: print(cls)

37 動態刪除屬性  

刪除對象的屬性

In [1]: delattr(xiaoming,'id')

In [2]: hasattr(xiaoming,'id')
Out[2]: False

38 一鍵查看對象所有方法 

不帶參數時返回當前範圍內的變量、方法和定義的類型列表;帶參數時返回參數的屬性,方法列表。

In [96]: dir(xiaoming)
Out[96]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',

'name']

39 動態獲取對象屬性 

獲取對象的屬性

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name

In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: getattr(xiaoming,'name') # 獲取xiaoming這個實例的name屬性值
Out[3]: 'xiaoming'

40 對象是否有這個屬性

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name

In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: hasattr(xiaoming,'name')
Out[3]: True

In [4]: hasattr(xiaoming,'address')
Out[4]: False

41 對象門牌號 

返回對象的內存地址

In [1]: id(xiaoming)
Out[1]: 98234208

42 isinstance

判斷object是否為類classinfo的實例,是返回true

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name

In [2]: xiaoming = Student(id='001',name='xiaoming')

In [3]: isinstance(xiaoming,Student)
Out[3]: True

43 父子關係鑑定

In [1]: class undergraduate(Student):
...: def studyClass(self):
...: pass
...: def attendActivity(self):
...: pass

In [2]: issubclass(undergraduate,Student)
Out[2]: True

In [3]: issubclass(object,Student)
Out[3]: False

In [4]: issubclass(Student,object)
Out[4]: True

如果class是classinfo元組中某個元素的子類,也會返回True

In [1]: issubclass(int,(int,float))
Out[1]: True

44 所有對象之根

object 是所有類的基類

In [1]: o = object()

In [2]: type(o)
Out[2]: object

45 創建屬性的兩種方式

返回 property 屬性,典型的用法:

class C:
def __init__(self):
self._x = None

def getx(self):
return self._x

def setx(self, value):
self._x = value

def delx(self):
del self._x
# 使用property類創建 property 屬性
x = property(getx, setx, delx, "I'm the 'x' property.")

使用python裝飾器,實現與上完全一樣的效果代碼:

class C:
def __init__(self):
self._x = None

@property
def x(self):
return self._x

@x.setter
def x(self, value):
self._x = value

@x.deleter
def x(self):
del self._x

46 查看對象類型

class type(name, bases, dict)

傳入一個參數時,返回 object 的類型:

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...:

In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: type(xiaoming)
Out[3]: __main__.Student

In [4]: type(tuple())
Out[4]: tuple

47 元類

xiaoming, xiaohong, xiaozhang 都是學生,這類群體叫做 Student.

Python 定義類的常見方法,使用關鍵字 class

In [36]: class Student(object):
...: pass

xiaoming, xiaohong, xiaozhang 是類的實例,則:

xiaoming = Student()
xiaohong = Student()
xiaozhang = Student()

創建後,xiaoming 的 __class__ 屬性,返回的便是 Student類

In [38]: xiaoming.__class__
Out[38]: __main__.Student

問題在於,Student 類有 __class__屬性,如果有,返回的又是什麼?

In [39]: xiaoming.__class__.__class__
Out[39]: type

哇,程序沒報錯,返回 type

那麼,我們不妨猜測:Student 類,類型就是 type

換句話說,Student類就是一個對象,它的類型就是 type

所以,Python 中一切皆對象,類也是對象

Python 中,將描述 Student 類的類被稱為:元類。

按照此邏輯延伸,描述元類的類被稱為:元元類,開玩笑了~ 描述元類的類也被稱為元類。

聰明的朋友會問了,既然 Student 類可創建實例,那麼 type 類可創建實例嗎?如果能,它創建的實例就叫:類 了。你們真聰明!

說對了,type 類一定能創建實例,比如 Student 類了。

In [40]: Student = type('Student',(),{})

In [41]: Student
Out[41]: __main__.Student

它與使用 class 關鍵字創建的 Student 類一模一樣。

Python 的類,因為又是對象,所以和 xiaoming,xiaohong 對象操作相似。支持:

In [43]: StudentMirror = Student # 類直接賦值 # 類直接賦值
In [44]: Student.class_property = 'class_property' # 添加類屬性
In [46]: hasattr(Student, 'class_property')
Out[46]: True

元類,確實使用不是那麼多,也許先了解這些,就能應付一些場合。就連 Python 界的領袖 Tim Peters 都說:

「元類就是深度的魔法,99%的用戶應該根本不必為此操心。

六、工具48 枚舉對象  

返回一個可以枚舉的對象,該對象的next()方法將返回一個元組。

In [1]: s = ["a","b","c"]
...: for i ,v in enumerate(s,1):
...: print(i,v)
...:
1 a
2 b
3 c

49 查看變量所佔字節數

In [1]: import sys

In [2]: a = {'a':1,'b':2.0}

In [3]: sys.getsizeof(a) # 佔用240個字節
Out[3]: 240

50 過濾器  

在函數中設定過濾條件,迭代元素,保留返回值為True的元素:

In [1]: fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])

In [2]: list(fil)
Out[2]: [11, 45, 13]

51 返回對象的哈希值  

返回對象的哈希值,值得注意的是自定義的實例都是可哈希的,list, dict, set等可變對象都是不可哈希的(unhashable)

In [1]: hash(xiaoming)
Out[1]: 6139638

In [2]: hash([1,2,3])
# TypeError: unhashable type: 'list'

52 一鍵幫助 

返回對象的幫助文檔

In [1]: help(xiaoming)
Help on Student in module __main__ object:

class Student(builtins.object)
| Methods defined here:
|
| __init__(self, id, name)
|
| __repr__(self)
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)

53 獲取用戶輸入 

獲取用戶輸入內容

In [1]: input()
aa
Out[1]: 'aa'

54 創建迭代器類型

使用iter(obj, sentinel), 返回一個可迭代對象, sentinel可省略(一旦迭代到此元素,立即終止)

In [1]: lst = [1,3,5]

In [2]: for i in iter(lst):
...: print(i)
...:
1
3
5

In [1]: class TestIter(object):
...: def __init__(self):
...: self.l=[1,3,2,3,4,5]
...: self.i=iter(self.l)
...: def __call__(self): #定義了__call__方法的類的實例是可調用的
...: item = next(self.i)
...: print ("__call__ is called,fowhich would return",item)
...: return item
...: def __iter__(self): #支持迭代協議(即定義有__iter__()函數)
...: print ("__iter__ is called!!")
...: return iter(self.l)
In [2]: t = TestIter()
In [3]: t() # 因為實現了__call__,所以t實例能被調用
__call__ is called,which would return 1
Out[3]: 1

In [4]: for e in TestIter(): # 因為實現了__iter__方法,所以t能被迭代
...: print(e)
...:
__iter__ is called!!
1
3
2
3
4
5

55 打開文件

返回文件對象

In [1]: fo = open('D:/a.txt',mode='r', encoding='utf-8')

In [2]: fo.read()
Out[2]: '\ufefflife is not so long,\nI use Python to play.'

mode取值表:

字符意義'r'讀取(默認)'w'寫入,並先截斷文件'x'排它性創建,如果文件已存在則失敗'a'寫入,如果文件存在則在末尾追加'b'二進位模式't'文本模式(默認)'+'打開用於更新(讀取與寫入)56 創建range序列

range(stop)

range(start, stop[,step])

生成一個不可變序列:

In [1]: range(11)
Out[1]: range(0, 11)

In [2]: range(0,11,1)
Out[2]: range(0, 11)

57 反向迭代器

In [1]: rev = reversed([1,4,2,3,1])

In [2]: for i in rev:
...: print(i)
...:
1
3
2
4
1

58 聚合迭代器

創建一個聚合了來自每個可迭代對象中的元素的迭代器:

In [1]: x = [3,2,1]
In [2]: y = [4,5,6]
In [3]: list(zip(y,x))
Out[3]: [(4, 3), (5, 2), (6, 1)]

In [4]: a = range(5)
In [5]: b = list('abcde')
In [6]: b
Out[6]: ['a', 'b', 'c', 'd', 'e']
In [7]: [str(y) + str(x) for x,y in zip(a,b)]
Out[7]: ['a0', 'b1', 'c2', 'd3', 'e4']

59 鏈式操作

from operator import (add, sub)


def add_or_sub(a, b, oper):
return (add if oper == '+' else sub)(a, b)


add_or_sub(1, 2, '-') # -1

60 對象序列化

對象序列化,是指將內存中的對象轉化為可存儲或傳輸的過程。很多場景,直接一個類對象,傳輸不方便。

但是,當對象序列化後,就會更加方便,因為約定俗成的,接口間的調用或者發起的 web 請求,一般使用 json 串傳輸。

實際使用中,一般對類對象序列化。先創建一個 Student 類型,並創建兩個實例。

class Student():
def __init__(self,**args):
self.ids = args['ids']
self.name = args['name']
self.address = args['address']
xiaoming = Student(ids = 1,name = 'xiaoming',address = '北京')
xiaohong = Student(ids = 2,name = 'xiaohong',address = '南京')

導入 json 模塊,調用 dump 方法,就會將列表對象 [xiaoming,xiaohong],序列化到文件 json.txt 中。

import json

with open('json.txt', 'w') as f:
json.dump([xiaoming,xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False, indent=2, sort_keys=True)

生成的文件內容,如下:

[
{
"address":"北京",
"ids":1,
"name":"xiaoming"
},
{
"address":"南京",
"ids":2,
"name":"xiaohong"
}
]

來源丨https://github.com/jackzhenguo/python-small-examples

相關焦點

  • 60 個 Python 闖關小例子,建議收藏
    26 函數的五類參數使用例子python五類參數:位置參數,關鍵字參數,默認參數,可變位置或關鍵字參數的使用。注意觀察參數a, 既可以f(1),也可以f(a=1) 其可讀性比第一種更好,建議使用f(a=1)。
  • 60個Python實用小例子,建議收藏(文末送書)
    🚀本文推出60個Python實用小例子,建議收藏,方便後期學習和回顧用。python五類參數:位置參數,關鍵字參數,默認參數,可變位置或關鍵字參數的使用。注意觀察參數a, 既可以f(1),也可以f(a=1) 其可讀性比第一種更好,建議使用f(a=1)。
  • 【必收藏系列】60個Python小例子
    26 函數的五類參數使用例子python五類參數:位置參數,關鍵字參數,默認參數,可變位置或關鍵字參數的使用。注意觀察參數a, 既可以f(1),也可以f(a=1) 其可讀性比第一種更好,建議使用f(a=1)。
  • 223個Python小例子(1-60)
    文末閱讀原文: 獲取2020年,最強Python學習資料Python小例子貢獻歡迎貢獻小例子到此庫小例子python五類參數:位置參數,關鍵字參數,默認參數,可變位置或關鍵字參數的使用。注意觀察參數a, 既可以f(1),也可以f(a=1) 其可讀性比第一種更好,建議使用f(a=1)。
  • 42個Python小例子
    60秒學會一個Python小例子。奔著此出發點,作者在過去1個月,將平時經常使用的代碼段換為小例子,分享出來後受到大家的喜歡。python')  # 13(個字節)str_byte_len('字符')  # 6(個字節)5 尋找第n次出現位置def search_n(s, c, n):    size = 0    for i, x in enumerate(s):        if x == c:            size +=
  • 絕對收藏的Python小例子(上)
    來源丨 https://github.com/jackzhenguo/python-small-examples
  • Python趣味打怪:60秒學會一個例子,147段代碼助你從入門到大師
    不要害怕學習的過程枯燥無味,這裡有程式設計師jackzhenguo打造的一份中文Python「糖果包」:147個代碼小樣,60秒一口,營養又好玩,從Python基礎到機器學習盡皆囊括。入門簡單如十進位轉二進位,盡顯Python簡潔之美:In [1]: bin(10)Out[1]: '0b1010'冬天到了,就算沒有點亮手繪技能,也能用簡單幾行代碼繪出漫天雪花:例子是有趣的例子
  • 告別枯燥,60 秒學會一個 Python 小例子
    本文推薦一個python的傻瓜式的學習資源,內容簡單易懂,讓人可以在60 秒學會一個 Python 小例子當前庫已有
  • ​【Python基礎】告別枯燥,60 秒學會一個 Python 小例子
    本文推薦一個python的傻瓜式的學習資源,內容簡單易懂,讓人可以在60 秒學會一個 Python 小例子當前庫已有 300多 個實用的小例子本文來源:https://github.com/jackzhenguo/python-small-examples文章轉自:機器學習初學者本庫目錄
  • 一個300多萬人玩的闖關趣味Python網站
    打開界面,小編就被深深的吸引,感覺有點想密室逃脫的感覺,而且找回了小時候遊戲界面的感覺。從遊戲的界面介紹可以看出,該遊戲一共有33關。而且每一關都是從界面給出的提示中找尋線索,並利用Python編程解決問題。小編立即開始了闖關。01.
  • 【python技能】Python要點總結,30個小例子剖析難易度,贈送海量學習福利
    -100']7列表中所有單詞都轉化為小寫:In[ 34]: a = [ 'Hello', 'World', '2019Python']In[ 35]: [w.lower forw ina]Out[ 35]: [ 'hello', 'world', '2019python']3.3 高級例子8
  • 20多個python實用小例子(1)
    我整理了 20多 個Python入門的小例子。方便同學們在實踐中能夠依葫蘆畫瓢,慢慢習慣使用python。如何加入python交流和答疑群:請需要的同學掃描下面二維碼,通過後會拉你進入交流群,請注意:關注公眾號。
  • 這42個Python小例子,太走心~
    告別枯燥,60秒學會一個Python小例子。奔著此出發點,我在過去1個月,將平時經常使用的代碼段換為小例子,分享出來後受到大家的喜歡。今天我完整梳理一遍,總結到這裡。很感謝這段時間,有3個小夥伴為此庫所做出的貢獻。希望更多朋友能分享平日使用的小例子,它們包括但不限於:Python基礎、Web開發、數據科學、機器學習的精簡小例子。
  • Python要點總結,我使用了100個小例子!
    -100']7列表中所有單詞都轉化為小寫:In [34]: a = ['Hello', 'World', '2019Python']In [35]: [w.lower() for w in a]Out[35]: ['hello', 'world', '2019python']3.3 高級例子8
  • 來闖關嗎?​一個有趣的 Python 解謎網站
    我們來玩玩看,點擊「get challenged」開始挑戰。nothing=12345').text 8url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?
  • ​【Python基礎】告別枯燥,60 秒學會一個 Python 小例子(文末下載)
    本文推薦一個python的傻瓜式的學習資源,內容簡單易懂,讓人可以在60 秒學會一個 Python 小例子當前庫已有 300多 個實用的小例子本文來源:https://github.com/jackzhenguo/python-small-examples資源下載:見文末本庫目錄
  • 一個go和python有趣的例子
    今天在一博文中看到一個有趣的問題,分享給大家,曾經也通過自學學習過python程式語言,python是一門很簡煉、功能豐富的語言,目前已大量用於科學研究和網際網路開發各個領域
  • 100個相見恨晚的Python庫(建議收藏)
    ,都不可避免的都要做一段時間的調包俠那就算是調包俠也都會有自己調包秘籍,拿出來能讓他人感嘆「相見恨晚」的那種Awesome Pythonawesome-python.com/在Github上有個awesome-python這麼個項目,能獲得110k stars
  • Python編程:Python3+PyCharm+PyQt5開發環境詳細配置,建議收藏
    Python3 + PyCharm + PyQt5開發環境詳細配置前兩天發布了個一個小視頻,詳細介紹了PyCharm開發環境下使用PyQt5界面庫進行Python開發的詳細配置過程,應小夥伴們的強烈要求,這次把文字版內容給大家整理出來了,大家喜歡的話快快收藏吧。
  • 原創通俗易懂的Python的正則表達式,建議收藏
    下面,我帶大家來一個入門demo例子,代碼如下:importrereg_string = "hello9527python@wangcai.@!下面是具體例子>>> importre>>> reg_string = "hello9527python@wangcai.@!