一、Python函數
Python是一個高級語言,它支持多種編程範式,其中函數式編程是其中之一。在Python中,函數式編程有著重要的地位,其強大且靈活的函數特性深受開發者和科學家的喜愛。Python函數是一段語句和演算法的封裝,其具有輸入、計算和輸出三個基本特徵。Python函數的定義以及函數的調用都非常方便,Python中的函數支持返回值,也支持函數內聲明嵌套函數。
def square(number):
"""計算輸入的數字的平方"""
return number ** 2
print(square(3)) # 9
二、Python All函數
Python內置函數all(),用來判斷可迭代對象中所有元素是否都為真值(True或者非零數值)。如果可迭代對象中所有元素都為真,那麼all函數返回True,否則返回False。
nums = [1, 2, 3, 4, 0]
print(all(nums)) # False
nums = [1, 2, 3, 4, 5]
print(all(nums)) # True
三、Python函數int
將字元串或數字轉換為整數的函數 int() 可以接受一個字元串或數字作為參數,返回一個整數值。如果參數是帶有小數點的字元串則會報錯,如需進行強制轉換需要使用float函數。
str_num = "123"
num = int(str_num)
print(type(num)) #
str_float = "123.45"
num = int(str_float) # 報錯
四、Python函數的靈活性
Python函數支持可變長度的參數,包括位置參數和關鍵字參數。其中 *args 用於表示位置參數,**kwargs用於表示關鍵字參數。
def test(*args):
for arg in args:
print(arg)
test(1, 2, 3, 4)
def test(**kwargs):
for key, value in kwargs.items():
print("{} : {}".format(key, value))
test(a=1, b=2, c=3)
五、Python函數len用法
Python內置函數len()用於返回一個對象的長度、元素個數或者位元組數。len()函數支持各種數據類型,包括字元串、元組、列表、字典、集合等等。
str = "Hello World"
print(len(str)) # 11
list = [1, 2, 3, 4, 5]
print(len(list)) # 5
六、Python bin函數
Python內置函數bin()用於返回一個整數的二進位表示。bin()函數的返回結果是一個字元串,該字元串的開頭是0b表示它是一個二進位字元串。
num = 10
print(bin(num)) # 0b1010
num = 100
print(bin(num)) # 0b1100100
七、Python函數 – 大全
Python內置了非常多的函數,在日常編程中需要掌握一些常用函數及其使用方法:
- 數學函數:abs(), pow(), round()
- 字元串函數:str(), format(), replace(), count()
- 列表函數:len(), max(), min(), sum()
- 字典函數:items(), keys(), values()
nums = [1, 2, 3, 4, 5]
print(len(nums)) # 5
print(max(nums)) # 5
print(sum(nums)) # 15
str = "Hello World"
print(str.replace("World", "Python")) # Hello Python
print(str.count("l")) # 3
dict = {"name": "Tom", "age": 18}
print(dict.keys()) # dict_keys(['name', 'age'])
八、Python函數shape函數
Python中並不支持矩陣運算,如果需要進行矩陣運算需要使用numpy庫,其中shape()函數用於獲取numpy數組的形狀,即行數和列數。
import numpy as np
arr1 = np.array([1, 2, 3, 4])
print(arr1.shape) # (4,)
arr2 = np.array([[1, 2], [3, 4], [5, 6]])
print(arr2.shape) # (3, 2)
九、Python函數與函數選取
Python函數的靈活性和多樣性為我們提供了很多選擇,然而如何在眾多Python函數中選擇合適的函數也需要我們具備一定經驗。通常我們需要根據操作對象的數據類型和操作目的去篩選和選擇相應的函數。
- 操作字元串時可以使用Python內置的字元串函數,如replace(), count(), split()等;
- 操作列表或元組時可以使用Python內置的列表函數或元組函數,如len(), max(), min(), sum()等;
- 操作字典時可以使用Python內置的字典函數,如items(), keys(), values()等;
- 操作numpy數組時可以使用numpy庫中提供的函數,如shape(), reshape(), transpose()等。
下面是一個使用Python內置函數和numpy函數的簡單例子,展示了如何根據不同的數據類型選擇相應的函數:
import numpy as np
str = "Hello World"
print(str.replace("World", "Python"))
nums = [1, 2, 3, 4, 5]
print(max(nums))
arr = np.array([1, 2, 3, 4])
print(arr.sum())
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/275639.html