13個你不知道的Python技巧
Python 是頂級編程語言之一,它具有許多程序員從未使用過的許多隱藏功能。本文,我將分享13個你可能從未使用過的 Python 特性。
Python 是頂級編程語言之一,它具有許多程序員從未使用過的許多隱藏功能。
本文,我將分享13個你可能從未使用過的 Python 特性。不浪費時間,讓我們開始吧。
1. 按步長取數(shù)
知識點: list[start:stop:step]
- start: 開始索引, 默認為0
- end: 結(jié)束索引, 默認為列表長度
- step: 步長, 默認為1, 可以為負數(shù), 如果為負數(shù), 則為倒序.
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]) # [] ??注意:步長為負數(shù)時,結(jié)果為空
print(data[7:1:-2]) # [8,6,4] # ?? index 屬于 [7 -> 1),步長為2。
2. find 方法
知識點:list.find(obj, [start, [stop]])
- list: 列表或者字符串
- obj: 查找的元素
- start: 開始索引, 默認為0
- stop: 結(jié)束索引, 默認為列表長度
找不到返回-1
x = "Hello From Python"
print(x.find("o")) # 4
print(x.find("o", 5)) # 8
print(x.find("From Python")) # 6
print(x.find("No exist")) # -1
3. iter() 和 next()
# iter() 函數(shù)用于將一個可迭代對象轉(zhuǎn)換為一個迭代器
# next() 函數(shù)用于獲取迭代器的下一個返回值
values = [1, 3, 4, 6]
values = iter(values)
print(next(values)) # 1
print(next(values)) # 3
print(next(values)) # 4
print(next(values)) # 6
print(next(values)) # StopIteration
4. 測試文檔
Doctest 功能將讓您測試您的功能并顯示您的測試報告。如果您檢查下面的示例,您需要在三重引號中編寫一個測試參數(shù),其中>>>是固定的語法,你可以增加測試案例,并運行它!如下所示:
# Doctest
from 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 * y
testmod(name='Mul')
# 輸出如下:
"""
**********************************************************************
File "main.py", line 10, in Mul.Mul
Failed example:
Mul(19, 20)
Expected:
39
Got:
380
**********************************************************************
1 items had failures:
1 of 2 in Mul.Mul
***Test Failed*** 1 failures.
"""
5. yield
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)
6. 字典缺失鍵的處理
dic = {1: "x", 2: "y"}
# 不能使用 dict_1[3] 獲取值
print(dic[3]) # Key Error
# 使用 get() 方法獲取值
print(dic.get(3)) # None
print(dic.get(3, "No")) # No
7.for-else, while-else
你知道 Python 支持帶有 for-else, while-else 嗎?這個 else 語句會在你的循環(huán)沒有中斷地運行完后執(zhí)行,如果中途中斷了循環(huán),則不會執(zhí)行。
# for-else
for x in range(5):
print(x)
else:
print("Loop Completed") # executed
# while-else
i = 0
while i < 5:
break
else:
print("Loop Completed") # Not executed
8. f-string的強大
a = "Python"
b = "Job"
# Way 1
string = "I looking for a {} Programming {}".format(a, b)
print(string) # I looking for a Python Programming Job
#Way 2
string = f"I looking for a {a} Programming "
print(string) # I looking for a Python Programming Job
9. 改變遞歸深度
這是 Python 的另一個重要特性,它可以讓您設置 Python 程序的遞歸限制。看一下下面的代碼示例以更好地理解:
import sys
print(sys.getrecursionlimit()) # 1000 默認值
sys.setrecursionlimit = 2000
print(sys.getrecursionlimit) # 2000
10. 條件賦值
條件賦值功能使用三元運算符,可以在特定條件下為變量賦值。看看下面的代碼示例:
x = 5 if 2 > 4 else 2
print(x) # 2
y = 10 if 32 > 41 else 24
print(y) # 24
11. 參數(shù)解包
您可以解壓縮函數(shù)中的任何可迭代數(shù)據(jù)參數(shù)。看看下面的代碼示例:
def func(a, b, c):
print(a, b, c)
x = [1, 2, 3]
y = {'a': 1, 'b': 2, 'c': 3}
func(*x) # 1 2 3
func(**y) # 1 2 3
12. 呼喚世界(沒啥用)
import __hello__ # 你猜輸出啥?
# other code
import os
print(os) # <module 'os' from '/usr/lib/python3.6/os.py'>
13. 多行字符串
此功能將向您展示如何編寫沒有三重引號的多行字符串??纯聪旅娴拇a示例:
# 多行字符串
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 Coding
Learning material then
welcome to py2fun.com
"""
print(str2) #和上面的是不同的,換行也會被輸出。
小節(jié)
這些就是今天分享的 Python 的 13 個特性,希望你覺得這篇文章讀起來有趣且有用。