11 個編程小技巧,使用起來更省心
正在學 Python 的你并不孤單,有我在這里陪著你每天學習一個 Python 小技術。今天我為初學者整理了 11 個編程小技巧,使用起來非常省心,相信你看完定會有所收獲。
1、合并(Merge)兩個字典
有兩個字典,dict1、dict2,想把 dict2 的內容合并(Merge)到 dict1 中,可以使用 dict1.update(dict2)
- In [1]: dict1 = { 'a': 1, 'b': 2}
- In [2]: dict2 = { 'b': 3, 'd': 4}
- In [3]: dict1.update(dict2)
- In [4]: dict1
- Out[4]: {'a': 1, 'b': 3, 'd': 4}
- In [5]:
2、合并(Merge)兩個字典,但不能改變原始字典
有兩個字典,dict1、dict2,現在要把 dict1、dict2 的內容合并(Merge)到 dict3 中,有兩種方法:
方法一
- dict3 = {}
- dict3.update(dict1)
- dict3.update(dict2)
方法二
- dict3 = {**dict1, **dict2}
方法二使用了 ** 來解包字典,非常簡潔和優雅,推薦使用。
3、對包含字典的列表進行排序
假如有這樣的列表:
[{"name": "張三", "age": 30 },{"name": "李四", "age": 10 },{"name": "王武", "age": 15 }]
其內部元素是一個字典,如何進行自定義排序呢?比如按照 age 進行排序:
- list1 = [{"name": "張三", "age": 30 },{"name": "李四", "age": 10 },{"name": "王武", "age": 15 }]
- list1.sort(key = lambda x: x["age"])
- print(list1)
- [{'name': '李四', 'age': 10},
- {'name': '王武', 'age': 15},
- {'name': '張三', 'age': 30}]
如果不能改變 list1 原有的次序,可以使用內建函數 sorted,sorted 返回排序后的結果,并不改變原始順序:
- list1 = [{"name": "張三", "age": 30 },{"name": "李四", "age": 10 },{"name": "王武", "age": 15 }]
- sorted_list = sorted(list1, key = lambda x: x["age"])
- print(sorted_list)
- [{'name': '李四', 'age': 10},
- {'name': '王武', 'age': 15},
- {'name': '張三', 'age': 30}]
4、檢查文件是否存在
方法一,使用 os.path 模塊
- In [2]: import os
- In [3]: if os.path.exists("/usr/bin/passwd"):
- ...: print("存在")
- ...:
- 存在
方法二、使用 pathlib(推薦使用)
- In [4]: from pathlib import Path
- In [5]: if Path("/usr/bin/passwd").exists():
- ...: print("存在")
- ...:
- 存在
關于 pathlib 為什么比 os.path 好用,可以閱讀求求你,別用 os.path 了。
5、獲取某個目錄最新的文件或目錄
- In [7]: import glob
- ...: import os
- ...:
- ...: list_of_files = glob.glob('/Users/aaron/*') # * means all if need specific format
- ...: then *.csv
- ...: latest_file = max(list_of_files, key=os.path.getctime)
- ...: print(latest_file)
- ...:
- /Users/aaron/web-service-gin
更推薦你使用 pathlib
- from pathlib import Path
- folder_path = Path('/Users/aaron')
- list_of_paths = folder_path.glob('*')
- latest_path = max(list_of_paths, key = lambda p: p.stat().st_ctime)
6、隨機密碼生成器
將以下內容保存為 generate_random_password.py:
- import string
- import random
- def generate_random_password():
- ## 輸入密碼長度
- length = int(input("請輸入密碼長度:"))
- ## 密碼字符范圍
- characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
- random.shuffle(characters)
- ## 隨機選擇字符
- password = []
- for i in range(length):
- password.append(random.choice(characters))
- random.shuffle(password)
- ## 現實生成的密碼
- print("".join(password))
- if __name__ == "__main__":
- generate_random_password()
執行結果
- python generate_random_password.py
- 請輸入密碼長度:6
- i3o!(o
7、將兩個列表轉換為一個字典
- list1 = ['a', 'b', 'c']
- list2 = [1, 2, 3]
- dictionary = dict(zip(list1, list2))
- print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
8、測量小代碼片段的執行時間
- import timeit
- start = timeit.default_timer()
- [i for i in range(100000)]
- stop = timeit.default_timer()
- print(stop - start)
timeit 是標準庫提供的計時工具,還可以在命令行這樣使用:
示例 1:命令行界面來比較三個不同的表達式。
- $ python3 -m timeit '"-".join(str(n) for n in range(100))'
- 10000 loops, best of 5: 30.2 usec per loop
- $ python3 -m timeit '"-".join([str(n) for n in range(100)])'
- 10000 loops, best of 5: 27.5 usec per loop
- $ python3 -m timeit '"-".join(map(str, range(100)))'
- 10000 loops, best of 5: 23.2 usec per loop
示例 2:通過代碼中比較三個不同的表達式。
- >>>
- >>> import timeit
- >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
- 0.3018611848820001
- >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
- 0.2727368790656328
- >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
- 0.23702679807320237
timeit 內部還可以傳入一個可調用對象:
- >>> def fun():
- ... return "-".join(map(str, range(100)))
- ...
- >>> import timeit
- >>> timeit.timeit(fun, number=10000)
- 0.16171755199999893
- >>>
9、統計列表中頻率最高的元素
- def most_frequent(list):
- return max(set(list), key=list.count)
- mylist = [1,1,2,3,4,5,5,1,2,1,]
- print("頻率最高的元素: ", most_frequent(mylist))
10、如何避免冗長的 if else 分支
簡單來說,就是借助于字典,把策略寫在字典里面,比如設計一個函數,計算兩個數的加、減、乘、除、n 次方
- def calculate(action_des: str, a:int,b:int) -> int:
- if action_des == '+':
- return a+b
- elif action_dex == '-':
- return a-b
- elif action_dex == '*':
- return a*b
- elif action_dex == '/':
- return a/b
- elif action_dex == '**':
- return a**b
借助于字典,可以不需要使用 if else:
- import operator
- def calculate(action_des: str, a:int,b:int) -> int:
- action = {
- "+": operator.add,
- "-": operator.sub,
- "/": operator.truediv,
- "*": operator.mul,
- "**": pow
- }
- return action[action_des](a, b)
這也是設計模式中的策略模式的最小示例。
11、讓列表內的元素隨機排列一下
- import random
- MyList = [1, 2, 3, 4]
- random.shuffle(MyList)
- print(MyList) # [3, 4, 2, 1]
最后
以上 11 個編程小技巧,如果有幫助,點個贊再滑走吧。
本文轉載自微信公眾號「 Python七號」,可以通過以下二維碼關注。轉載本文請聯系 Python七號公眾號。