很多時(shí)候你需要計(jì)算某段代碼執(zhí)行所需的時(shí)間,可以使用 time
模塊來實(shí)現(xiàn)這個(gè)功能。
華坪網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),華坪網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為華坪成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的華坪做網(wǎng)站的公司定做!
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.e-07
不使用循環(huán),找出兩個(gè)列表的差異,可以使用集合的 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']
需要調(diào)用字符串的 join
方法,還可以設(shè)置間隔符,下面為間隔符為空格的例子。
a = ["Python", "Is", "Great"]
print(" ".join(a))
# output
Python Is Great
在 C 中不能連續(xù)進(jìn)行大小比較,在 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
一行代碼,即可將嵌套列表轉(zhuǎn)換為一個(gè)列表。
import itertools
a = [[1, 2], [3, 4], [5, 6]]
print(list(itertools.chain.from_iterable(a)))
# output
[1, 2, 3, 4, 5, 6]
要聲明一些小功能,但不使用常規(guī)的聲明方式,可以用使用 lambda
。 python 中的 lambda 關(guān)鍵字為聲明匿名函數(shù)提供了快捷方式。
subtract = lambda x, y : x-y
subtract(5, 4)
# 可結(jié)合map reduce使用
Counter(list).most_common(n)
根據(jù)列表 / 字符串中每個(gè)元素出現(xiàn)次數(shù),降序返回列表 / 字符串中的前 n 個(gè)元素,其中 n 是指定的數(shù)字。在元組中返回各個(gè)元素及其出現(xiàn)的次數(shù)。
# 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)]
輸出結(jié)果為個(gè)數(shù)最多的 3 個(gè)數(shù)字,其中 1 出現(xiàn) 5 次,3 出現(xiàn) 4 次,4 出現(xiàn) 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) 也可以實(shí)現(xiàn)同樣功能,但列表數(shù)據(jù)量大時(shí)會(huì)變慢
# s.count(x) x在s中出現(xiàn)的總次數(shù)
# output
4
當(dāng)你要使用任何數(shù)據(jù)結(jié)構(gòu)(例如列表,字典或任何對(duì)象)來存儲(chǔ)值或記錄時(shí),可以檢查數(shù)據(jù)結(jié)構(gòu)使用了多少內(nèi)存。
使用 sys
模塊中定義的 sys.getsizeof
函數(shù)獲取內(nèi)置對(duì)象使用的內(nèi)存,返回對(duì)象的大?。ㄒ宰止?jié)為單位)。
import sys
x = 1
print(sys.getsizeof(x))
# output
28
注意:sys.getsizeof
不會(huì)為第三方對(duì)象或用戶定義的對(duì)象返回正確的值。
n = 3
a = "Python"
print(a * n)
# output
PythonPythonPython
當(dāng)你需要連接許多迭代器對(duì)象(如列表)以獲取單個(gè)列表時(shí),可以使用 zip
函數(shù),結(jié)果顯示每個(gè)新列表每個(gè)元素,是所有迭代器對(duì)象同一位置值的元組。
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)]
通過 []
方式獲取字典中的值時(shí),如果鍵不存在則會(huì)報(bào)錯(cuò),可以使用字典的 get
函數(shù),指定鍵不存在時(shí),可以返回的值。
比如字典中有鍵 ‘c’,則返回對(duì)應(yīng)的值,否則返回 3。
d = {'a':1, 'b':2}
print(d.get('c', 3))
# output
3
for...else...
Python 中的 for 循環(huán)可以使用 else
關(guān)鍵字,如果在 for 循環(huán)中遇到 break
跳出循環(huán),則不執(zhí)行 else
子句,否則執(zhí)行。
for i in range(5):
pass
else:
pass
{**d1, **d2}
合并字典d1 = {'a': 1}
d2 = {'b': 2}
print({**d1, **d2})
# output
{'a': 1, 'b': 2}
使用 heapq
返回任何列表中的前 n 個(gè)最小 / 最大元素,這里 n 是指定的數(shù)字。
# 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]
輸出的第一行給出列表等級(jí)中存在的最大數(shù)字中的 3 個(gè)。 同樣,輸出的第二行將打印出列表等級(jí)中存在的最小元素中的 4 個(gè),此功能的另一個(gè)特點(diǎn)是它不會(huì)忽略重復(fù)值。
x, y = y, x
就地交換兩個(gè)數(shù)字x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
# output
10 20
20 10
set(listNumbers)
從列表中刪除重復(fù)項(xiàng)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]
假設(shè)你有兩個(gè)包含相同元素的列表,但是兩個(gè)列表中的元素順序都不同??梢允褂?collections.Counter()
方法進(jìn)行判斷,確定它們是否元素值都相同。
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
要將字節(jié)轉(zhuǎn)換為字符串,可以對(duì) bytes
對(duì)象進(jìn)行解碼以生成字符串。
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))
將兩個(gè)列表轉(zhuǎn)換成字典例如你有兩個(gè)列表,一個(gè)列表包含鍵,第二個(gè)列表包含對(duì)應(yīng)的值,想將這兩個(gè)列表轉(zhuǎn)換為一個(gè)字典??梢允褂?zip
函數(shù)來進(jìn)行實(shí)現(xiàn)。
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 個(gè)小數(shù)位的任何浮點(diǎn)數(shù)。 例如 73.4(73.40)和 288.5400(88.54)。
number= 88.2345
print('{0:.2f}'.format(number))
s.ljust(10, '-')
字符串左對(duì)齊填充到10左對(duì)齊函數(shù) ljust
和右對(duì)齊函數(shù) rjust
,都需要指定字符串長(zhǎng)度,以及想要填充的字符,不指定則默認(rèn)填充空格。
s = ""
print(s.ljust(10, '-'))
print(s.rjust(10, '0'))
# output
-----
00000
https://www.zhihu.com/people/zhao-xiao-de-93/posts
網(wǎng)站名稱:一些實(shí)驗(yàn)中用過的python函數(shù)/方法(持續(xù)更新)
分享路徑:http://chinadenli.net/article42/dsogjhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、商城網(wǎng)站、靜態(tài)網(wǎng)站、網(wǎng)站導(dǎo)航、手機(jī)網(wǎng)站建設(shè)、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容