20條非常實(shí)用的Python代碼,建議收藏!
Python一直以來被詬病速度慢,影響開發(fā)效率,希望這次Guido老爺子能幫python打一場漂亮的翻身仗。
這篇文章不準(zhǔn)備介紹Python速度如何,而是給大家?guī)硪恍┏S们覍?shí)用的Python代碼實(shí)例,幾乎是開發(fā)者必備的知識點(diǎn)。
1、合并兩個(gè)字典
Python3.5之后,合并字典變得容易起來。我們可以通過**符號解壓字典,并將多個(gè)字典傳入{}中,實(shí)現(xiàn)合并。
def Merge(dict1, dict2):
res = {**dict1, **dict2}
return res
# 兩個(gè)字典
dict1 = {"name": "Joy", "age": 25}
dict2 = {"name": "Joy", "city": "New York"}
dict3 = Merge(dict1, dict2)
print(dict3)
輸出:
{'name': 'Joy', 'age': 25, 'city': 'New York'}
2、鏈?zhǔn)奖容^
python有鏈?zhǔn)奖容^的機(jī)制,在一行里支持多種運(yùn)算符比較。相當(dāng)于拆分多個(gè)邏輯表達(dá)式,再進(jìn)行邏輯與操作。
a = 5
print(2 < a < 8)
print(1 == a < 3)
輸出:
True
False
3、重復(fù)打印字符串
將一個(gè)字符串重復(fù)打印多次,一般使用循環(huán)實(shí)現(xiàn),但有更簡易的方式可以實(shí)現(xiàn)。
n = 5
string = "Hello!"
print(string * n)
輸出:
Hello!Hello!Hello!Hello!Hello!
4、檢查文件是否存在
我們知道Python有專門處理系統(tǒng)交互的模塊-os,它可以處理文件的各種增刪改查操作。
那如何檢查一個(gè)文件是否存在呢?os模塊可以輕松實(shí)現(xiàn)。
from os import path
def check_for_file():
print("Does file exist:", path.exists("data.csv"))
if __name__=="__main__":
check_for_file()
輸出:
Does file exist: False
5、檢索列表最后一個(gè)元素
在使用列表的時(shí)候,有時(shí)會(huì)需要取最后一個(gè)元素,有下面幾種方式可以實(shí)現(xiàn)。
my_list = ['banana', 'apple', 'orange', 'pineapple']
#索引方法
last_element = my_list[-1]
#pop方法
last_element = my_list.pop()
輸出:
'pineapple'
6、列表推導(dǎo)式
列表推導(dǎo)式是for循環(huán)的簡易形式,可以在一行代碼里創(chuàng)建一個(gè)新列表,同時(shí)能通過if語句進(jìn)行判斷篩選
def get_vowels(string):
return [vowel for vowel in string if vowel in 'aeiou']
print("Vowels are:", get_vowels('This is some random string'))
輸出:
Vowels are: ['i', 'i', 'o', 'e', 'a', 'o', 'i']
7、計(jì)算代碼執(zhí)行時(shí)間
python中time模塊提供了時(shí)間處理相關(guān)的各種函數(shù)方法,我們可以使用它來計(jì)算代碼執(zhí)行的時(shí)間。
import time
start_time = time.time()
total = 0
for i in range(10):
total += i
print("Sum:", total)
end_time = time.time()
time_taken = end_time - start_time
print("Time: ", time_taken)
輸出:
Sum: 45
Time: 0.0009975433349609375
8、查找出現(xiàn)次數(shù)最多的元素
使用max方法找出列表中出現(xiàn)次數(shù)最多的元素。
def most_frequent(list):
return max(set(list), key=list.count)
mylist = [1,1,2,3,4,5,6,6,2,2]
print("出現(xiàn)次數(shù)最多的元素是:", most_frequent(mylist))
輸出:
出現(xiàn)次數(shù)最多的元素是: 2
9、將兩個(gè)列表轉(zhuǎn)換為字典
有兩個(gè)列表,將列表A里的元素作為鍵,將列表B里的對應(yīng)元素作為值,組成一個(gè)字典。
def list_to_dictionary(keys, values):
return dict(zip(keys, values))
list1 = [1, 2, 3]
list2 = ['one', 'two', 'three']
print(list_to_dictionary(list1, list2))
輸出:
{1: 'one', 2: 'two', 3: 'three'}
10、異常處理
Python提供了try...except...finally的方式來處理代碼異常,當(dāng)然還有其他組合的方式。
a, b = 1,0
try:
print(a/b)
except ZeroDivisionError:
print("Can not divide by zero")
finally:
print("Executing finally block")
輸出:
Can not divide by zero
Executing finally block
11、反轉(zhuǎn)字符串
使用切片操作對字符串進(jìn)行反轉(zhuǎn),這是比較直接有效的方式。這也可以用來檢測回文數(shù)。
str = "Hello World"
print("反轉(zhuǎn)后字符串是:", str[::-1])
輸出:
反轉(zhuǎn)后字符串是: dlroW olleH
12、字符串列表組成單個(gè)字符串
使用join方法將字符串列表組成單個(gè)字符串。
list = ["Hello", "world", "Ok", "Bye!"]
combined_string = " ".join(list)
print(combined_string)
輸出:
Hello world Ok Bye!
13、返回字典缺失鍵的默認(rèn)值
字典中的get方法用于返回指定鍵的值,如果鍵不在字典中返回默認(rèn)值 None 或者設(shè)置的默認(rèn)值。
dict = {1:'one', 2:'two', 4:'four'}
#returning three as default value
print(dict.get(3, 'three'))
print("原始字典:", dict)
輸出:
three
原始字典: {1: 'one', 2: 'two', 4: 'four'}
14、交換兩個(gè)變量的值
在不使用臨時(shí)變量的前提下,交換兩個(gè)變量的值。
a, b = 5, 10
# 方法1
a, b = b, a
# 方法2
def swap(a,b):
return b,a
swap(a,b)
15、正則表達(dá)式
正則表達(dá)式用來匹配處理字符串,python中的re模塊提供了全部的正則功能。
import re
text = "The rain in spain"
result = re.search("rain", text)
print(True if result else False)
輸出:
True
16、篩選值
python中的filter方法可以用來進(jìn)行值的篩選。
my_list = [0,1,2,3,6,7,9,11]
result = filter(lambda x: x % 2!=0, my_list)
print(list(result))
輸出:
[1, 3, 7, 9, 11]
17、統(tǒng)計(jì)字頻
判斷字符串每個(gè)元素出現(xiàn)的次數(shù),可以用collections模塊中的Counter方法來實(shí)現(xiàn),非常簡潔。
from collections import Counter
result = Counter('banana')
print(result)
輸出:
Counter({'a': 3, 'n': 2, 'b': 1})
18、變量的內(nèi)存占用
如何輸出python中變量的內(nèi)存占用大小,可以通過sys模塊來實(shí)現(xiàn)。
import sys
var1 = 15
list1 = [1,2,3,4,5]
print(sys.getsizeof(var1))
print(sys.getsizeof(list1))
輸出:
28
104
19、鏈?zhǔn)胶瘮?shù)調(diào)用
在一行代碼中調(diào)用多個(gè)函數(shù)。
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 5, 10
print((add if b > a else subtract)(a,b))
輸出:
15
20、從列表中刪除重復(fù)項(xiàng)
刪除列表中重復(fù)項(xiàng)一般可以通過遍歷來篩選去重,或者直接使用集合方法。
list1 = [1,2,3,3,4,'John', 'Ana', 'Mark', 'John']
# 方法1
def remove_duplicate(list_value):
return list(set(list_value))
print(remove_duplicate(list1))
# 方法2
result = []
[result.append(x) for x in list1 if x not in result]
print(result)
輸出:
[1, 2, 3, 4, 'Ana', 'John', 'Mark']
[1, 2, 3, 4, 'John', 'Ana', 'Mark']
推薦閱讀:
入門: 最全的零基礎(chǔ)學(xué)Python的問題 | 零基礎(chǔ)學(xué)了8個(gè)月的Python | 實(shí)戰(zhàn)項(xiàng)目 |學(xué)Python就是這條捷徑
干貨:爬取豆瓣短評,電影《后來的我們》 | 38年NBA最佳球員分析 | 從萬眾期待到口碑撲街!唐探3令人失望 | 笑看新倚天屠龍記 | 燈謎答題王 |用Python做個(gè)海量小姐姐素描圖 |碟中諜這么火,我用機(jī)器學(xué)習(xí)做個(gè)迷你推薦系統(tǒng)電影
趣味:彈球游戲 | 九宮格 | 漂亮的花 | 兩百行Python《天天酷跑》游戲!
AI: 會(huì)做詩的機(jī)器人 | 給圖片上色 | 預(yù)測收入 | 碟中諜這么火,我用機(jī)器學(xué)習(xí)做個(gè)迷你推薦系統(tǒng)電影
小工具: Pdf轉(zhuǎn)Word,輕松搞定表格和水印! | 一鍵把html網(wǎng)頁保存為pdf!| 再見PDF提取收費(fèi)! | 用90行代碼打造最強(qiáng)PDF轉(zhuǎn)換器,word、PPT、excel、markdown、html一鍵轉(zhuǎn)換 | 制作一款釘釘?shù)蛢r(jià)機(jī)票提示器! |60行代碼做了一個(gè)語音壁紙切換器天天看小姐姐!|
年度爆款文案
2).學(xué)Python真香!我用100行代碼做了個(gè)網(wǎng)站,幫人PS旅行圖片,賺個(gè)雞腿吃
9).發(fā)現(xiàn)一個(gè)舔狗福利!這個(gè)Python爬蟲神器太爽了,自動(dòng)下載妹子圖片
點(diǎn)閱讀原文,領(lǐng)AI全套資料!


