Python內置函數是預先編寫好的,可以直接使用,無需自己編寫。使用內置函數可以提高代碼的效率和可讀性。以下是一些使用內置函數的例子:
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # 輸出:5
my_list = [1, 2, 3, 4, 5]
maximum = max(my_list)
print(maximum) # 輸出:5
my_list = [1, 2, 3, 4, 5]
minimum = min(my_list)
print(minimum) # 輸出:1
my_list = [1, 2, 3, 4, 5]
total = sum(my_list)
print(total) # 輸出:15
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]
my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
print(index, value)
# 輸出:
# 0 apple
# 1 banana
# 2 cherry
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped)) # 輸出:[(1, 'a'), (2, 'b'), (3, 'c')]
def square(x):
return x * x
my_list = [1, 2, 3, 4, 5]
squared_list = list(map(square, my_list))
print(squared_list) # 輸出:[1, 4, 9, 16, 25]
def is_even(x):
return x % 2 == 0
my_list = [1, 2, 3, 4, 5]
even_list = list(filter(is_even, my_list))
print(even_list) # 輸出:[2, 4]
from functools import reduce
def add(x, y):
return x + y
my_list = [1, 2, 3, 4, 5]
total = reduce(add, my_list)
print(total) # 輸出:15
這些內置函數的使用可以大大提高代碼的效率和可讀性。當然,Python還有很多其他的內置函數,可以根據實際需求選擇合適的函數來優化代碼。