一些實驗中用過的python函數(shù)/方法(持續(xù)更新)

衡量運行時間

很多時候你需要計算某段代碼執(zhí)行所需的時間,可以使用 time 模塊來實現(xiàn)這個功能。

華坪網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),華坪網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為華坪成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請找那個售后服務(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),找出兩個列表的差異,可以使用集合的 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']

翻轉(zhuǎn)字符串和列表

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ù)進行大小比較,在 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'>

二維列表轉(zhuǎn)一維列表

只需使用 Itertools 一行代碼,即可將嵌套列表轉(zhuǎn)換為一個列表。

import itertools  
a = [[1, 2], [3, 4], [5, 6]] 
print(list(itertools.chain.from_iterable(a))) 

# output
[1, 2, 3, 4, 5, 6]

Lambda 匿名函數(shù)用法

要聲明一些小功能,但不使用常規(guī)的聲明方式,可以用使用 lambda。 python 中的 lambda 關(guān)鍵字為聲明匿名函數(shù)提供了快捷方式。

subtract = lambda x, y : x-y
subtract(5, 4)
# 可結(jié)合map reduce使用

列表中每個元素出現(xiàn)次數(shù)

Counter(list).most_common(n)根據(jù)列表 / 字符串中每個元素出現(xiàn)次數(shù),降序返回列表 / 字符串中的前 n 個元素,其中 n 是指定的數(shù)字。在元組中返回各個元素及其出現(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é)果為個數(shù)最多的 3 個數(shù)字,其中 1 出現(xiàn) 5 次,3 出現(xiàn) 4 次,4 出現(xiàn) 3 次。

找到列表中最常出現(xiàn)的值

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] 
print(max(set(test), key = test.count))
# max(test, key = test.count) 也可以實現(xiàn)同樣功能,但列表數(shù)據(jù)量大時會變慢
# s.count(x) x在s中出現(xiàn)的總次數(shù)
# output
4

檢查對象的內(nèi)存使用情況

當你要使用任何數(shù)據(jù)結(jié)構(gòu)(例如列表,字典或任何對象)來存儲值或記錄時,可以檢查數(shù)據(jù)結(jié)構(gòu)使用了多少內(nèi)存。

使用 sys 模塊中定義的 sys.getsizeof 函數(shù)獲取內(nèi)置對象使用的內(nèi)存,返回對象的大?。ㄒ宰止?jié)為單位)。

import sys 
x = 1
print(sys.getsizeof(x)) 

# output
28

注意:sys.getsizeof 不會為第三方對象或用戶定義的對象返回正確的值。

字符串乘法拼接

n = 3
a = "Python"
print(a * n)

# output
PythonPythonPython

將多個列表同一位置元素zip在一起

當你需要連接許多迭代器對象(如列表)以獲取單個列表時,可以使用 zip 函數(shù),結(jié)果顯示每個新列表每個元素,是所有迭代器對象同一位置值的元組。

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 函數(shù),指定鍵不存在時,可以返回的值。

比如字典中有鍵 ‘c’,則返回對應的值,否則返回 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}

求列表中前 n 個最大 / 最小的數(shù)字

使用 heapq 返回任何列表中的前 n 個最小 / 最大元素,這里 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]

輸出的第一行給出列表等級中存在的最大數(shù)字中的 3 個。 同樣,輸出的第二行將打印出列表等級中存在的最小元素中的 4 個,此功能的另一個特點是它不會忽略重復值。

x, y = y, x 就地交換兩個數(shù)字

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]

比較兩個無序列表

假設(shè)你有兩個包含相同元素的列表,但是兩個列表中的元素順序都不同??梢允褂?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

字節(jié)轉(zhuǎn)換為字符串

要將字節(jié)轉(zhuǎn)換為字符串,可以對 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))將兩個列表轉(zhuǎn)換成字典

例如你有兩個列表,一個列表包含鍵,第二個列表包含對應的值,想將這兩個列表轉(zhuǎn)換為一個字典??梢允褂?zip 函數(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'}

設(shè)置小數(shù)位格式

你要顯示帶有 2 個小數(shù)位的任何浮點數(shù)。 例如 73.4(73.40)和 288.5400(88.54)。

number= 88.2345
print('{0:.2f}'.format(number))

s.ljust(10, '-') 字符串左對齊填充到10

左對齊函數(shù) ljust 和右對齊函數(shù) rjust,都需要指定字符串長度,以及想要填充的字符,不指定則默認填充空格。

s = ""
print(s.ljust(10, '-'))
print(s.rjust(10, '0'))

# output
-----
00000

https://www.zhihu.com/people/zhao-xiao-de-93/posts

網(wǎng)站名稱:一些實驗中用過的python函數(shù)/方法(持續(xù)更新)
分享路徑:http://m.kartarina.com/article42/dsogjhc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、商城網(wǎng)站、靜態(tài)網(wǎng)站、網(wǎng)站導航、手機網(wǎng)站建設(shè)App開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)
主站蜘蛛池模板: 国产AV无码专区亚洲AV男同| 亚洲AV永久青草无码精品| 久久久久久久亚洲Av无码| 人妻丝袜中文无码av影音先锋专区| 中文字幕精品三区无码亚洲| 精品无码专区亚洲| 亚洲成A人片在线观看无码3D| 无码囯产精品一区二区免费| 日韩AV无码精品一二三区| 无码少妇一区二区| 全免费a级毛片免费看无码| 中文字幕乱码人妻无码久久| 亚洲国产成人精品无码区花野真一| 精品无码一级毛片免费视频观看| 99无码精品二区在线视频| 国产丝袜无码一区二区三区视频| 在人线av无码免费高潮喷水| 亚洲AV无码专区国产乱码4SE| 国产品无码一区二区三区在线| 日韩欧精品无码视频无删节| 中文无码久久精品| 免费无遮挡无码视频在线观看| 高清无码v视频日本www| 亚洲V无码一区二区三区四区观看| 久久久国产精品无码一区二区三区| 久久无码人妻一区二区三区 | 久青草无码视频在线观看| 亚洲av成人无码久久精品| 亚洲最大av无码网址| 精品无码国产一区二区三区麻豆| 伊人久久精品无码麻豆一区| 免费A级毛片av无码| 久久午夜无码鲁丝片直播午夜精品| 精品无码国产污污污免费网站国产| 成人无码区免费视频观看| 无码中文字幕一区二区三区| 亚洲av无码专区在线电影天堂| 伊人无码精品久久一区二区| 亚洲国产精品无码久久九九大片 | 亚洲av无码一区二区三区观看| 国产成A人亚洲精V品无码|