18luck网站

18luck网站電子設計 | 18luck网站Rss 2.0 會員中心 會員注冊
搜索: 您現在的位置: 18luck网站 >> 編程學習 >> Python >> 正文

python案例代碼_20條非常實用的Python代碼實例

作者:佚名    文章來源:網友    點擊數:    更新時間:2023/10/31

據說Python之父-Guido Van Rossum打算讓CPython更快,速度直接翻五倍,這是實實在在的好消息。

Python一直以來被詬病速度慢,影響開發效率,希望這次Guido老爺子能幫python打一場漂亮的翻身仗。

這篇文章不準備介紹Python速度如何,而是給大家帶來一些常用且實用的Python代碼實例,幾乎是開發者必備的知識點。

1、合並兩個字典

Python3.5之後,合並字典變得容易起來。我們(men) 可以通過**符號解壓字典,並將多個(ge) 字典傳(chuan) 入{}中,實現合並。

def Merge(dict1, dict2): res = {**dict1, **dict2} return res # 兩(liang) 個(ge) 字典 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、鏈式比較

python有鏈式比較的機製,在一行裏支持多種運算符比較。相當於(yu) 拆分多個(ge) 邏輯表達式,再進行邏輯與(yu) 操作。

a = 5 print(2 < a < 8) print(1 == a < 3)

輸出:

True False

3、重複打印字符串

將一個(ge) 字符串重複打印多次,一般使用循環實現,但有更簡易的方式可以實現。

n = 5 string = "Hello!" print(string * n)

輸出:

Hello!Hello!Hello!Hello!Hello!

4、檢查文件是否存在

我們(men) 知道Python有專(zhuan) 門處理係統交互的模塊-os,它可以處理文件的各種增刪改查操作。

那如何檢查一個(ge) 文件是否存在呢?os模塊可以輕鬆實現。

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、檢索列表最後一個(ge) 元素

在使用列表的時候,有時會(hui) 需要取最後一個(ge) 元素,有下麵幾種方式可以實現。

my_list = ['banana', 'apple', 'orange', 'pineapple'] #索引方法 last_element = my_list[-1] #pop方法 last_element = my_list.pop()

輸出:

'pineapple'

6、列表推導式

列表推導式是for循環的簡易形式,可以在一行代碼裏創建一個(ge) 新列表,同時能通過if語句進行判斷篩選

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、計算代碼執行時間

python中time模塊提供了時間處理相關(guan) 的各種函數方法,我們(men) 可以使用它來計算代碼執行的時間。

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、查找出現次數最多的元素

使用max方法找出列表中出現次數最多的元素。

def most_frequent(list): return max(set(list), key=list.count) mylist = [1,1,2,3,4,5,6,6,2,2] print("出現次數最多的元素是:", most_frequent(mylist))

輸出:

出現次數最多的元素是: 2

9、將兩(liang) 個(ge) 列表轉換為(wei) 字典

有兩(liang) 個(ge) 列表,將列表A裏的元素作為(wei) 鍵,將列表B裏的對應元素作為(wei) 值,組成一個(ge) 字典。

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的方式來處理代碼異常,當然還有其他組合的方式。

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、反轉字符串

使用切片操作對字符串進行反轉,這是比較直接有效的方式。 這也可以用來檢測回文數。

str = "Hello World" print("反轉後字符串是:", str[::-1])

輸出:

反轉後字符串是: dlroW olleH

12、字符串列表組成單個(ge) 字符串

使用join方法將字符串列表組成單個(ge) 字符串。

list = ["Hello", "world", "Ok", "Bye!"] combined_string = " ".join(list) print(combined_string)

輸出:

Hello world Ok Bye!

13、返回字典缺失鍵的默認值

字典中的get方法用於(yu) 返回指定鍵的值,如果鍵不在字典中返回默認值 None 或者設置的默認值。

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、交換兩(liang) 個(ge) 變量的值

在不使用臨(lin) 時變量的前提下,交換兩(liang) 個(ge) 變量的值。

a, b = 5, 10 # 方法1 a, b = b, a # 方法2 def swap(a,b): return b,a swap(a,b)

15、正則表達式

正則表達式用來匹配處理字符串,python中的re模塊提供了全部的正則功能。

import re text = "The rain in spain" result = re.search("rain", text) print(True if result else False)

輸出:

True

16、篩選值

python中的filter方法可以用來進行值的篩選。

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、統計字頻

判斷字符串每個(ge) 元素出現的次數,可以用collections模塊中的Counter方法來實現,非常簡潔。

from collections import Counter result = Counter('banana') print(result)

輸出:

Counter({'a': 3, 'n': 2, 'b': 1})

18、變量的內(nei) 存占用

如何輸出python中變量的內(nei) 存占用大小,可以通過sys模塊來實現。

import sys var1 = 15 list1 = [1,2,3,4,5] print(sys.getsizeof(var1)) print(sys.getsizeof(list1))

輸出:

28 104

19、鏈式函數調用

在一行代碼中調用多個(ge) 函數。

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、從(cong) 列表中刪除重複項

刪除列表中重複項一般可以通過遍曆來篩選去重,或者直接使用集合方法。

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']
Tags:Python,案例,代碼,實例代碼  
責任編輯:admin
請文明參與討論,禁止漫罵攻擊。 昵稱:注冊  登錄
[ 查看全部 ] 網友評論
關於我們 - 聯係我們 - 廣告服務 - 友情鏈接 - 網站地圖 - 版權聲明 - 在線幫助 - 文章列表
返回頂部
刷新頁麵
下到頁底
晶體管查詢