python 20條實用代碼


20條Python代碼實例

1、合並兩個字典

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

def Merge(dict1, dict2): 
    res = {**dict1, **dict2} 
    return res 
      
# 兩個字典
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有鏈式比較的機制,在一行里支持多種運算符比較。相當於拆分多個邏輯表達式,再進行邏輯與操作。

a = 5

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

輸出:

True
False

3、重復打印字符串

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

n = 5
string = "Hello!"

print(string * n)

輸出:

Hello!Hello!Hello!Hello!Hello!

4、檢查文件是否存在

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

那如何檢查一個文件是否存在呢?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、檢索列表最后一個元素

在使用列表的時候,有時會需要取最后一個元素,有下面幾種方式可以實現。

my_list = ['banana''apple''orange''pineapple']

#索引方法
last_element = my_list[-1]

#pop方法
last_element = my_list.pop()

輸出:

'pineapple'

6、列表推導式

列表推導式是for循環的簡易形式,可以在一行代碼里創建一個新列表,同時能通過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模塊提供了時間處理相關的各種函數方法,我們可以使用它來計算代碼執行的時間。

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、將兩個列表轉換為字典

有兩個列表,將列表A里的元素作為鍵,將列表B里的對應元素作為值,組成一個字典。

def list_to_dictionary(keys, values):
  return dict(zip(keys, values))

list1 = [123]
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、字符串列表組成單個字符串

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

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

print(combined_string)

輸出:

Hello world Ok Bye!

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

字典中的get方法用於返回指定鍵的值,如果鍵不在字典中返回默認值 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、交換兩個變量的值

在不使用臨時變量的前提下,交換兩個變量的值。

a, b = 510

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

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

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

輸出:

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

18、變量的內存占用

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

import sys

var1 = 15
list1 = [1,2,3,4,5]

print(sys.getsizeof(var1))
print(sys.getsizeof(list1))

輸出:

28
104

19、鏈式函數調用

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

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

a, b = 510

print((add if b > a else subtract)(a,b))

輸出:

15

20、從列表中刪除重復項

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

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']

28
104

21、pprint的使用

用pprint打印會豎起來打印 (復雜的字典或者嵌套的很長的序列)

from pprint import pprint
response = {"title": "「圖解年報」瑞凌股份:2020年歸母凈利潤為6688萬元,同比下降41.2%", "pred": "營收", "short_name": "瑞凌股份", "company_id": 1611}
print(response)
pprint(response)

輸出:

 

22 解析電子表格

import csv
csv_mapping_list = []
with open("/path/to/data.csv") as my_data:
    csv_reader = csv.reader(my_data, delimiter=",")
    line_count = 0
    for line in csv_reader:
        if line_count == 0:
            header = line
        else:
            row_dict = {key: value for key, value in zip(header, line)}
            csv_mapping_list.append(row_dict)
        line_count += 1
CSV 模塊

 

23 將兩個或多個列表合並為一個列表

例如,如果我有 4 個列表 [1,2,3]、['a','b','c']、['h','e','y'], 和[4,5,6],我們想為這四個列表創建一個新列表;它將是 [[1,'a','h',4], [2,'b','e',5], [3,'c','y',6]] 。
def merge(*args, missing_val = None):
    max_length = max([len(lst) for lst in args])
    outList = []
    for i in range(max_length):
        outList.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])
    return outList

merge([1,2,3],['a','b','c'],['h','e','y'],[4,5,6])
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM