Python 是頂級編程語言之一,它具有許多程序員從未使用過的許多隱藏功能。本文,我將分享13個你可能從未使用過的 Python 特性。
Python 是頂級編程語言之一,它具有許多程序員從未使用過的許多隱藏功能。
本文,我將分享13個你可能從未使用過的 Python 特性。不浪費時間,讓我們開始吧。
知識點: list[start:stop:step]
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]print(data[::2]) # [1, 3, 5, 7, 9]print(data[::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]print(data[2:7:-2]) # [] ??注意:步長為負(fù)數(shù)時,結(jié)果為空print(data[7:1:-2]) # [8,6,4] # ?? index 屬于 [7 -> 1),步長為2。
知識點:list.find(obj, [start, [stop]])
找不到返回-1
x = "Hello From Python"print(x.find("o")) # 4print(x.find("o", 5)) # 8print(x.find("From Python")) # 6print(x.find("No exist")) # -1
# iter() 函數(shù)用于將一個可迭代對象轉(zhuǎn)換為一個迭代器# next() 函數(shù)用于獲取迭代器的下一個返回值values = [1, 3, 4, 6]values = iter(values)print(next(values)) # 1print(next(values)) # 3print(next(values)) # 4print(next(values)) # 6print(next(values)) # StopIteration
Doctest 功能將讓您測試您的功能并顯示您的測試報告。如果您檢查下面的示例,您需要在三重引號中編寫一個測試參數(shù),其中>>>是固定的語法,你可以增加測試案例,并運行它!如下所示:
# Doctestfrom doctest import testmod def Mul(x, y) -> int: """ This function returns the mul of x and y argumets incoking the function followed by expected output: >>> Mul(4, 5) 20 >>> Mul(19, 20) 39 """ return x * ytestmod(name='Mul')# 輸出如下:"""**********************************************************************File "main.py", line 10, in Mul.MulFailed example: Mul(19, 20)Expected: 39Got: 380**********************************************************************1 items had failures: 1 of 2 in Mul.Mul***Test Failed*** 1 failures."""
yield 語句是 Python 的另一個令人驚奇的特性,它的工作方式類似于 return 語句。但它不是終止函數(shù)并返回,而是返回到它返回給調(diào)用者的地方。
yield 返回的是一個生成器??梢允褂?nbsp;next() 函數(shù)來獲取生成器的下一個值。也可以使用 for 循環(huán)來遍歷生成器。
def func(): print(1) yield "a" print(2) yield "aa" print(3) yield "aaa"print(list(func())) ## ['a', 'aa', 'aaa']for x in func(): print(x)
dic = {1: "x", 2: "y"}# 不能使用 dict_1[3] 獲取值print(dic[3]) # Key Error# 使用 get() 方法獲取值print(dic.get(3)) # Noneprint(dic.get(3, "No")) # No
你知道 Python 支持帶有 for-else, while-else 嗎?這個 else 語句會在你的循環(huán)沒有中斷地運行完后執(zhí)行,如果中途中斷了循環(huán),則不會執(zhí)行。
# for-elsefor x in range(5): print(x)else: print("Loop Completed") # executed# while-elsei = 0 while i < 5: breakelse: print("Loop Completed") # Not executed
a = "Python"b = "Job"# Way 1string = "I looking for a {} Programming {}".format(a, b)print(string) # I looking for a Python Programming Job#Way 2string = f"I looking for a {a} Programming "print(string) # I looking for a Python Programming Job
這是 Python 的另一個重要特性,它可以讓您設(shè)置 Python 程序的遞歸限制??匆幌孪旅娴拇a示例以更好地理解:
import sysprint(sys.getrecursionlimit()) # 1000 默認(rèn)值sys.setrecursionlimit = 2000print(sys.getrecursionlimit) # 2000
條件賦值功能使用三元運算符,可以在特定條件下為變量賦值??纯聪旅娴拇a示例:
x = 5 if 2 > 4 else 2print(x) # 2y = 10 if 32 > 41 else 24print(y) # 24
您可以解壓縮函數(shù)中的任何可迭代數(shù)據(jù)參數(shù)??纯聪旅娴拇a示例:
def func(a, b, c): print(a, b, c)x = [1, 2, 3]y = {'a': 1, 'b': 2, 'c': 3}func(*x) # 1 2 3func(**y) # 1 2 3
import __hello__ # 你猜輸出啥?# other codeimport osprint(os) # <module 'os' from '/usr/lib/python3.6/os.py'>
此功能將向您展示如何編寫沒有三重引號的多行字符串。看看下面的代碼示例:
# 多行字符串str1= "Are you looking for free Coding " /"Learning material then " /"welcome to py2fun.com"print(str1) # Are you looking for free Coding Learning material then welcome to Medium.com# 三重引號字符串str2 = """Are you looking for free CodingLearning material then welcome to py2fun.com"""print(str2) #和上面的是不同的,換行也會被輸出。
這些就是今天分享的 Python 的 13 個特性,希望你覺得這篇文章讀起來有趣且有用。
本文鏈接:http://www.tebozhan.com/showinfo-26-51221-0.html13個你不知道的Python技巧
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 九個必須知道的Python字典騷操作