干貨滿滿,30個Python源代碼!


1.十進制轉換為二進制

>>> bin(10) '0b1010'

2.十進制轉換為八進制

>>> oct(9) '0o11'

3.十進制轉換為十六進制

>>> hex(15) '0xf'

4.字符串轉換為字節類型

>>> s = "apple" >>> bytes(s,encoding='utf-8') b'apple'

5.字符類型、數值型等轉換為字符串類型

>>> i = 100 >>> str(i) '100'

6.十進制整數對應的 ASCII 字符

>>> chr(65) 'A'

7.ASCII字符對應的十進制數

>>> ord('A') 65

8.整數或數值型字符串轉換為浮點數

>>> float(3) 3.0

9.創建數據字典的幾種方法

>>> dict() {} >>> dict(a='a',b='b') {'a': 'a', 'b': 'b'} >>> dict(zip(['a','b'],[1,2])) {'a': 1, 'b': 2} >>> dict([('a',1),('b',2)]) {'a': 1, 'b': 2}

10.排序函數

>>> a = [1,4,2,3,1] #降序 >>> sorted(a,reverse=True) [4, 3, 2, 1, 1] >>> a = [{'name':'xiaoming','age':18,'gender':'male'}, {'name':'xiaohong','age':20,'gender':'female'}] #按 age升序 >>> sorted(a,key=lambda x: x['age'],reverse=False) [{'name': 'xiaoming', 'age': 18, 'gender': 'male'}, {'name': 'xiaohong', 'age': 20, 'gender': 'female'}]

11.求和函數

>>> a = [1,4,2,3,1] >>> sum(a) 11 #求和初始值為1 >>> sum(a,1) 12

12.計算字符串型表達式的值

>>> s = "1 + 3 +5" >>> eval(s) 9 >>> eval('[1,3,5]*3') [1, 3, 5, 1, 3, 5, 1, 3, 5]

13.獲取用戶輸入內容

>>> input() I'm typing "I'm typing "

14.print 用法

>>> lst = [1,3,5] # f 打印 >>> print(f'lst: {lst}') lst: [1, 3, 5] # format 打印 >>> print('lst:{}'.format(lst)) lst:[1, 3, 5]

15.格式化字符串常見用法

>>> print("i am {0},age {1}".format("tom",18)) i am tom,age 18 >>> print("{:.2f}".format(3.1415926)) # 保留小數點后兩位 3.14 >>> print("{:+.2f}".format(-1)) # 帶符號保留小數點后兩位 -1.00 >>> print("{:.0f}".format(2.718)) # 不帶小數位 3 >>> print("{:0>3d}".format(5)) # 整數補零,填充左邊, 寬度為3 005 >>> print("{:,}".format(10241024)) # 以逗號分隔的數字格式 10,241,024 >>> print("{:.2%}".format(0.718)) # 百分比格式 71.80% >>> print("{:.2e}".format(10241024)) # 指數記法 1.02e+07

值(值得注意,自定義的實例都可哈希,listdictset等可變對象都不可哈希)

>>> class Student(): def __init__(self,id,name): self.id = id self.name = name >>> xiaoming = Student('001','xiaoming') >>> hash(xiaoming) -9223371894234104688

16.if not x

直接使用 x 和 not x 判斷 x 是否為 None 或空

x = [1,3,5] if x: print('x is not empty ') if not x: print('x is empty')

17.打開文件,並返回文件對象

>>> import os >>> os.chdir('D:/source/dataset') >>> os.listdir() ['drinksbycountry.csv', 'IMDB-Movie-Data.csv', 'movietweetings', 'titanic_eda_data.csv', 'titanic_train_data.csv'] >>> o = open('drinksbycountry.csv',mode='r',encoding='utf-8') >>> o.read() "country,beer_servings,spirit_servings,wine_servings,total_litres_of_pur e_alcohol,continent\nAfghanistan,0,0,0,0.0,Asia\nAlbania,89,132,54,4.9,"

18. 創建迭代器

>>> class TestIter(): def __init__(self,lst): self.lst = lst # 重寫可迭代協議__iter__ def __iter__(self): print('__iter__ is called') return iter(self.lst)

迭代 TestIter 類:

>>> t = TestIter() >>> t = TestIter([1,3,5,7,9]) >>> for e in t: print(e) __iter__ is called 1 3 5 7 9

19.創建range迭代器

>>> t = range(11) >>> t = range(0,11,2) >>> for e in t: print(e) 0 2 4 6 8 10

20.反向

>>> rev = reversed([1,4,2,3,1]) >>> for i in rev: print(i) 1 3 2 4 1

21.打包

>>> x = [3,2,1] >>> y = [4,5,6] >>> list(zip(y,x)) [(4, 3), (5, 2), (6, 1)] >>> for i,j in zip(y,x): print(i,j) 4 3 5 2 6 1

22.過濾器

函數通過 lambda 表達式設定過濾條件,保留 lambda 表達式為True的元素:

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

23. split 分割**

>>> 'i love python'.split(' ') ['i', 'love', 'python']

24. 提取后綴名

>>> import os >>> os.path.splitext('D:/source/dataset/new_file.txt') ('D:/source/dataset/new_file', '.txt') #[1]:后綴名

25.斐波那契數列前n項

>>> def fibonacci(n): a, b = 1, 1 for _ in range(n): yield a a, b = b, a+b # 注意這種賦值 >>> for fib in fibonacci(10): print(fib) 1 1 2 3 5 8 13 21 34 55

26.list 等分 n 組

>>> from math import ceil >>> def divide_iter(lst, n): if n <= 0: yield lst return i, div = 0, ceil(len(lst) / n) while i < n: yield lst[i * div: (i + 1) * div] i += 1 >>> for group in divide_iter([1,2,3,4,5],2): print(group) [1, 2, 3] [4, 5]

27. 列表生成式

data = [1, 2, 3, 5, 8] result = [i * 2 for i in data if i & 1] # 奇數則乘以2 print(result) # [2, 6, 10]

28.字典生成式

keys = ['a', 'b', 'c'] values = [1, 3, 5] d = {k: v for k, v in zip(keys, values)} print(d)

29.判斷字符串是否包含某個子串,使用in明顯更加可讀

x = 'zen_of_python' if 'zen' in x: print('zen is in')

30.zip 打包

使用 zip 打包后結合 for 使用輸出一對

keys = ['a', 'b', 'c'] values = [1, 3, 5] for k, v in zip(keys, values): print(k, v)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM