Python中那些簡單又好用的特性和用法盤點
Python作為我的主力語言幫助我開發(fā)了許多DevOps運維自動化系統(tǒng),這篇文章總結(jié)幾個我在編寫Python代碼過程中用到的幾個簡單又好用的特性和用法,這些特性和用法可以幫助我們更高效地編寫Python代碼
1.鏈?zhǔn)奖容^
x = 5
y = 10
z = 15
if x < y < z:
print("x is less than y and y is less than z")
2.鏈?zhǔn)劫x值
total_regions = region_total_instances = total_instances = 0
3.三元運算符
x = 10 result = "Greater than 10" if x > 10 else "Less than or equal to 10"
4.使用args和kwargs傳遞多個位置參數(shù)或關(guān)鍵字參數(shù)給函數(shù)
def example_function(*args, **kwargs):
for arg in args:
# 執(zhí)行相關(guān)操作
for key, value in kwargs.items():
# 執(zhí)行相關(guān)操作
5.使用enumerate函數(shù)同時獲取索引和值
my_list = ['apple', 'banana', 'orange']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
6.使用zip函數(shù)同時迭代多個可迭代對象
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for item1, item2 in zip(list1, list2):
print(f"Item from list1: {item1}, Item from list2: {item2}")
7.使用itertools模塊進行迭代器和循環(huán)的高級操作
import itertools
for item in itertools.chain([1, 2, 3], ['a', 'b', 'c']):
print(item)
8.使用collections.Counter進行計數(shù)
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(my_list)
print(counter) # 輸出為Counter({'apple': 3, 'banana': 2, 'orange': 1})
9.使用any和all函數(shù)對可迭代對象中的元素進行邏輯判斷
my_list = [True, False, True, True] print(any(my_list)) # 輸出為True print(all(my_list)) # 輸出為False
10.使用sorted函數(shù)對可迭代對象進行排序
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_list = sorted(my_list) print(sorted_list) # 輸出為[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
11.使用set進行集合操作
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
print(set1.union(set2)) # 輸出為{1, 2, 3, 4, 5, 6, 7}
print(set1.intersection(set2)) # 輸出為{3, 4, 5}
12.上下文管理器
class CustomContextManager:
def __enter__(self):
# 在代碼塊執(zhí)行之前執(zhí)行的操作
# 可以返回一個值,該值將被賦值給as子句中的變量
def __exit__(self, exc_type, exc_val, exc_tb):
# 在代碼塊執(zhí)行之后執(zhí)行的操作
# 可以處理異常,返回True表示異常被處理,F(xiàn)alse則會重新拋出異常
# 使用自定義上下文管理器
with CustomContextManager() as obj:
# 在這里執(zhí)行一些操作
13.生成器表達式
# 使用生成器表達式計算1到10的平方和 squared_sum = sum(x**2 for x in range(1, 11)) print(squared_sum)
14.使用str.endswith()方法來檢查字符串是否以元組中的任何一個字符串結(jié)尾
filename = "example.csv"
if filename.endswith((".csv", ".xls", ".xlsx")):
# 執(zhí)行相關(guān)操作
同樣的用法還有str.startswith()來檢查字符串是否以元組中的任何一個字符串開頭
15.else語句與for和while循環(huán)結(jié)合使用
for item in some_list:
if condition:
# 執(zhí)行相關(guān)操作
break
else:
# 如果循環(huán)自然結(jié)束,執(zhí)行相關(guān)操作
16.靜態(tài)類型檢查
# 使用mypy進行靜態(tài)類型檢查
def add_numbers(a: int, b: int) -> int:
return a + b
result = add_numbers(5, 10)
print(result)
先總結(jié)這么多,歡迎補充
到此這篇關(guān)于Python中那些簡單又好用的特性和用法盤點的文章就介紹到這了,更多相關(guān)Python特性和用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python基礎(chǔ)之編碼規(guī)范總結(jié)
今天帶大家來學(xué)習(xí)python基礎(chǔ)知識,文中對python編碼規(guī)范作了詳細(xì)的介紹,對正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
python高級搜索實現(xiàn)高效搜索GitHub資源
這篇文章主要為大家介紹了python高級搜索來高效搜索GitHub,從而高效獲取所需資源,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11
基于MSELoss()與CrossEntropyLoss()的區(qū)別詳解
今天小編就為大家分享一篇基于MSELoss()與CrossEntropyLoss()的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

