衡量運行時間
很多時候你需要計算某段代碼執行所需的時間,可以使用 time 模塊來實作這個功能,
import time
startTime = time.time()
# write your code or functions calls
endTime = time.time()
totalTime = endTime - startTime
print("Total time required to execute code is =", totalTime)
# output
Total time required to execute code is = 4.76837158203125e-07
獲取兩個串列之間的差異
不使用回圈,找出兩個串列的差異,可以使用集合的 symmetric_difference 方法,
list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
list2 = ['Scott', 'Eric', 'Kelly']
set1 = set(list1)
set2 = set(list2)
list3 = list(set1.symmetric_difference(set2))
print(list3)
# output
['Emma', 'Smith']
翻轉字串和串列
a = "zhihu"
print("Reverse is", a[::-1])
List = ["Shriya", "Lavina", "Sampreeti" ]
List.reverse()
print(List)
# output
Reverse is uhihz
['Sampreeti', 'Lavina', 'Shriya']
連接串列中的多個字串
需要呼叫字串的 join 方法,還可以設定間隔符,下面為間隔符為空格的例子,
a = ["Python", "Is", "Great"]
print(" ".join(a))
# output
Python Is Great
同時使用多個比較運算子
在 C 中不能連續進行大小比較,在 Python 中就可以,
n = 10
result = 1 < n < 20
print(result)
result = 1 < n <= 9
print(result)
# output
True
False
列印匯入模塊的檔案路徑
import os
import socket
print(os)
print(socket)
# output
<module 'os' from 'D:\\Users\\xxx\\miniconda3\\envs\\xin\\lib\\os.py'>
<module 'socket' from 'D:\\Users\\xxx\\miniconda3\\envs\\xin\\lib\\socket.py'>
二維串列轉一維串列
只需使用 Itertools 一行代碼,即可將嵌套串列轉換為一個串列,
import itertools
a = [[1, 2], [3, 4], [5, 6]]
print(list(itertools.chain.from_iterable(a)))
# output
[1, 2, 3, 4, 5, 6]
Lambda 匿名函式用法
要宣告一些小功能,但不使用常規的宣告方式,可以用使用 lambda, python 中的 lambda 關鍵字為宣告匿名函式提供了快捷方式,
subtract = lambda x, y : x-y
subtract(5, 4)
# 可結合map reduce使用
串列中每個元素出現次數
Counter(list).most_common(n) 根據串列 / 字串中每個元素出現次數,降序回傳串列 / 字串中的前 n 個元素,其中 n 是指定的數字,在元組中回傳各個元素及其出現的次數,
# Code to find top 3 elements and their counts
# using most_common
from collections import Counter
arr = [1, 3, 4, 1, 2, 1, 1, 3, 4, 3, 5, 1, 2, 5, 3, 4, 5]
counter = Counter(arr)
top_three = counter.most_common(3)
print(top_three)
# output
[(1, 5), (3, 4), (4, 3)]
輸出結果為個數最多的 3 個數字,其中 1 出現 5 次,3 出現 4 次,4 出現 3 次,
找到串列中最常出現的值
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
# max(test, key = test.count) 也可以實作同樣功能,但串列資料量大時會變慢
# s.count(x) x在s中出現的總次數
# output
4
檢查物件的記憶體使用情況
當你要使用任何資料結構(例如串列,字典或任何物件)來存盤值或記錄時,可以檢查資料結構使用了多少記憶體,
使用 sys 模塊中定義的 sys.getsizeof 函式獲取內置物件使用的記憶體,回傳物件的大小(以位元組為單位),
import sys
x = 1
print(sys.getsizeof(x))
# output
28
注意:sys.getsizeof 不會為第三方物件或用戶定義的物件回傳正確的值,
字串乘法拼接
n = 3
a = "Python"
print(a * n)
# output
PythonPythonPython
將多個串列同一位置元素zip在一起
當你需要連接許多迭代器物件(如串列)以獲取單個串列時,可以使用 zip 函式,結果顯示每個新串列每個元素,是所有迭代器物件同一位置值的元組,
Year = (1999, 2003, 2011, 2017)
Month = ("Mar", "Jun", "Jan", "Dec")
Day = (11,21,13,5)
print(zip(Year, Month, Day))
# output
[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]
.get獲取字典中key對應的值,不存在則回傳指定值
通過 [] 方式獲取字典中的值時,如果鍵不存在則會報錯,可以使用字典的 get 函式,指定鍵不存在時,可以回傳的值,
比如字典中有鍵 ‘c’,則回傳對應的值,否則回傳 3,
d = {'a':1, 'b':2}
print(d.get('c', 3))
# output
3
for...else...
Python 中的 for 回圈可以使用 else 關鍵字,如果在 for 回圈中遇到 break 跳出回圈,則不執行 else 子句,否則執行,
for i in range(5):
pass
else:
pass
{**d1, **d2}合并字典
d1 = {'a': 1}
d2 = {'b': 2}
print({**d1, **d2})
# output
{'a': 1, 'b': 2}
求串列中前 n 個最大 / 最小的數字
使用 heapq 回傳任何串列中的前 n 個最小 / 最大元素,這里 n 是指定的數字,
# Python code to find 3 largest and 4 smallest
# elements of a list.
import heapq
grades = [110, 25, 38, 49, 20, 95, 33, 87, 80, 90]
print(heapq.nlargest(3, grades))
print(heapq.nsmallest(4, grades))
# output
[110, 95, 90]
[20, 25, 33, 38]
輸出的第一行給出串列等級中存在的最大數字中的 3 個, 同樣,輸出的第二行將列印出串列等級中存在的最小元素中的 4 個,此功能的另一個特點是它不會忽略重復值,
x, y = y, x 就地交換兩個數字
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
# output
10 20
20 10
set(listNumbers)從串列中洗掉重復項
listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]
print("Original= ", listNumbers)
listNumbers = list(set(listNumbers))
print("After removing duplicate= ", listNumbers)
# output
Original= [20, 22, 24, 26, 28, 28, 20, 30, 24]
After removing duplicate= [20, 22, 24, 26, 28, 30]
比較兩個無序串列
假設你有兩個包含相同元素的串列,但是兩個串列中的元素順序都不同,可以使用 collections.Counter()方法進行判斷,確定它們是否元素值都相同,
from collections import Counter
one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]
print("two lists are equal.", Counter(one) == Counter(two))
# output
two lists are equal.
檢查串列中的所有元素是否唯一
def isUnique(item):
tempSet = set()
return not any(i in tempSet or tempSet.add(i) for i in item)
listOne = [123, 345, 456, 23, 567]
print("All List elemtnts are Unique ", isUnique(listOne))
listTwo = [123, 345, 567, 23, 567]
print("All List elemtnts are Unique ", isUnique(listTwo))
# output
All List elemtnts are Unique True
All List elemtnts are Unique False
位元組轉換為字串
要將位元組轉換為字串,可以對 bytes 物件進行解碼以生成字串,
byteVar = b"pynative"
str = str(byteVar.decode("utf-8"))
print("Byte to string is" , str )
# output
Byte to string is pynative
dict(zip(ItemId, names))將兩個串列轉換成字典
例如你有兩個串列,一個串列包含鍵,第二個串列包含對應的值,想將這兩個串列轉換為一個字典,可以使用 zip 函式來進行實作,
ItemId = [54, 65, 76]
names = ["Hard Disk", "Laptop", "RAM"]
itemDictionary = dict(zip(ItemId, names))
print(itemDictionary)
# output
{54: 'Hard Disk', 65: 'Laptop', 76: 'RAM'}
設定小數位格式
你要顯示帶有 2 個小數位的任何浮點數, 例如 73.4(73.40)和 288.5400(88.54),
number= 88.2345
print('{0:.2f}'.format(number))
s.ljust(10, '-') 字串左對齊填充到10
左對齊函式 ljust 和右對齊函式 rjust,都需要指定字串長度,以及想要填充的字符,不指定則默認填充空格,
s = "12345"
print(s.ljust(10, '-'))
print(s.rjust(10, '0'))
# output
12345-----
0000012345
https://www.zhihu.com/people/zhao-xiao-de-93/posts
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479223.html
標籤:Python
