當前位置: 妍妍網 > 碼農

整理了60個Python小例子,拿來即用!

2024-05-06碼農

點選上方 " Python人工智慧技術 " 關註, 星標或者置頂

22點24分準時推播,第一時間送達

後台回復「 大禮包 」,送你特別福利

編輯:樂樂 | 來自:https://github.com/jackzhenguo/python-small-examples

上一篇:

正文

大家好,我是Python人工智慧技術

今天給大家分享一下60個Python小例子,拿來即用!

一、 數位

1 求絕對值

絕對值或復數的模

# 公眾號:快學Python
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 [1]: print("i am {0},age{1}".format("tom",18))
Out[1]:i am tom,age18


三、 函式

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
# 公眾號:快學Python
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))

輸出:

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) ,需要在前面添加一個星號:

deff(*,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))

有兩點疑惑:

  • 參數 v 的取值?

  • lambda 函式有返回值嗎?如果有,返回值是多少?

  • 呼叫上面函式,求出以下三個最長的列表:

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

    程式完整執行過程,動畫演示如下:

    結論:

  • 參數v的可能取值為 *lists ,也就是 tuple 的一個元素。

  • lambda 函式返回值,等於 lambda v 冒號後運算式的返回值。

  • 四、 數據結構

    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_sub class__',
    '__le__',
    '__lt__',
    '__module__',
    '__ne__',
    '__new__',
    '__reduce__',
    '__reduce_ex__',
    '__repr__',
    '__setattr__',
    '__sizeof__',
    '__str__',
    '__sub classhook__',
    '__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 study class(self):
    ...: pass
    ...: def attendActivity(self):
    ...: pass
    In [2]: issub class(undergraduate,Student)
    Out[2]: True
    In [3]: issub class(object,Student)
    Out[3]: False
    In [4]: issub class(Student,object)
    Out[4]: True

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

    In [1]: issub class(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取值表:

    56 建立range序列

    1. range(stop)

    2. 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"
    }
    ]

    萬水千山總是情,點個 👍 行不行

    為了跟上AI時代我幹了一件事兒,我建立了一個知識星球社群:ChartGPT與副業。想帶著大家一起探索 ChatGPT和新的AI時代

    有很多小夥伴搞不定ChatGPT帳號,於是我們決定,凡是這三天之內加入ChatPGT的小夥伴,我們直接送一個正常可用的永久ChatGPT獨立帳戶。

    不光是增長速度最快,我們的星球品質也絕對經得起考驗,短短一個月時間,我們的課程團隊釋出了 8個專欄、18個副業計畫

    簡單說下這個星球能給大家提供什麽:

    1、不斷分享如何使用ChatGPT來完成各種任務,讓你更高效地使用ChatGPT,以及副業思考、變現思路、創業案例、落地案例分享。

    2、分享ChatGPT的使用方法、最新資訊、商業價值。

    3、探討未來關於ChatGPT的機遇,共同成長。

    4、幫助大家解決ChatGPT遇到的問題。

    5、 提供一整年的售後服務,一起搞副業

    星球福利:

    1、加入星球4天後,就送ChatGPT獨立帳號。

    2、邀請你加入ChatGPT會員交流群。

    3、贈送一份完整的ChatGPT手冊和66個ChatGPT副業賺錢手冊。

    其它福利還在籌劃中... 不過,我給你大家保證,加入星球後,收獲的價值會遠遠大於今天加入的門票費用 !

    本星球第一期原價 399 ,目前屬於試營運,早鳥價 169 ,每超過50人漲價10元,星球馬上要來一波大的漲價,如果你還在猶豫,可能最後就要以 更高價格加入了 。。

    早就是優勢。建議大家盡早以便宜的價格加入!

    歡迎有需要的同學試試,如果本文對您有幫助,也請幫忙點個 贊 + 在看 啦!❤️

    在 還有更多優質計畫系統學習資源,歡迎分享給其他同學吧!

    你還有什 麽想要補充的嗎?

    免責聲明:本文內容來源於網路,文章版權歸原作者所有,意在傳播相關技術知識&行業趨勢,供大家學習交流,若涉及作品版權問題,請聯系刪除或授權事宜。

    技術君個人微信

    添加技術君個人微信即送一份驚喜大禮包

    → 技術資料共享

    → 技術交流社群

    --END--

    往日熱文:

    Python程式設計師深度學習的「四大名著」:

    這四本書著實很不錯!我們都知道現在機器學習、深度學習的資料太多了,面對海量資源,往往陷入到「無從下手」的困惑出境。而且並非所有的書籍都是優質資源,浪費大量的時間是得不償失的。給大家推薦這幾本好書並做簡單介紹。

    獲得方式:

    1.掃碼關註本公眾號

    2.後台回復關鍵詞:名著

    ▲長按掃描關註,回復名著即可獲取