# Python容器的內置通用函數怎么使用
Python提供了多種內置容器類型(如列表、元組、字典、集合等),這些容器不僅用于存儲數據,還提供了豐富的內置方法來操作數據。本文將詳細介紹Python容器的通用內置函數及其使用方法。
## 一、通用操作函數
### 1. `len()` - 獲取容器長度
```python
my_list = [1, 2, 3, 4]
length = len(my_list) # 返回4
max()
/min()
- 獲取最大/最小值numbers = [5, 2, 8, 1]
print(max(numbers)) # 8
print(min(numbers)) # 1
sum()
- 求和(僅限數值型容器)nums = [1.5, 2.5, 3.5]
total = sum(nums) # 7.5
sorted()
- 返回排序后的新列表chars = ['d', 'a', 'c']
sorted_chars = sorted(chars) # ['a', 'c', 'd']
reversed()
- 返回反轉迭代器rev_iter = reversed([1, 2, 3])
print(list(rev_iter)) # [3, 2, 1]
list()
- 轉換為列表tuple_data = (1, 2, 3)
list_data = list(tuple_data) # [1, 2, 3]
tuple()
- 轉換為元組set_data = {1, 2, 3}
tuple_data = tuple(set_data) # (1, 2, 3)
set()
- 轉換為集合(自動去重)list_with_dupes = [1, 2, 2, 3]
unique_set = set(list_with_dupes) # {1, 2, 3}
dict()
- 創建字典key_value_pairs = [('a', 1), ('b', 2)]
new_dict = dict(key_value_pairs) # {'a': 1, 'b': 2}
enumerate()
- 獲取索引和值for index, value in enumerate(['a', 'b', 'c']):
print(f"Index {index}: {value}")
zip()
- 并行迭代多個容器names = ['Alice', 'Bob']
scores = [85, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
filter()
- 過濾元素def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4]
evens = list(filter(is_even, numbers)) # [2, 4]
map()
- 對每個元素應用函數def square(x):
return x ** 2
squared = list(map(square, [1, 2, 3])) # [1, 4, 9]
in
操作符if 'a' in ['a', 'b', 'c']:
print("Found!")
any()
/all()
- 存在/全部滿足條件conditions = [True, False, True]
print(any(conditions)) # True
print(all(conditions)) # False
# 獲取字符串列表中所有長度大于3的字符串
words = ['apple', 'bat', 'car']
long_words = [w for w in words if len(w) > 3] # ['apple']
# 創建字符到ASCII碼的映射
chars = ['a', 'b', 'c']
char_to_ascii = {c: ord(c) for c in chars}
# {'a': 97, 'b': 98, 'c': 99}
# 展平二維列表
matrix = [[1, 2], [3, 4]]
flat = [num for row in matrix for num in row] # [1, 2, 3, 4]
時間復雜度比較:
len()
: O(1)x in list
: O(n)x in set
: O(1)內存效率:
sum(x*x for x in range(1000)) # 生成器表達式
dict1 = {'a': 1}
dict2 = {'b': 2}
merged = {**dict1, **dict2} # Python 3.5+
stats = {'a': 10, 'b': 15}
max_key = max(stats, key=stats.get) # 'b'
for i, v in enumerate(['a', 'b', 'c']):
print(i, v)
Python容器的內置通用函數提供了強大的數據操作能力,掌握這些函數可以: 1. 減少代碼量 2. 提高可讀性 3. 提升運行效率
建議在實際開發中多使用這些內置函數,而不是手動實現類似功能。隨著Python版本的更新,這些函數也在不斷優化,通常比自定義實現性能更好。
注意:本文示例基于Python 3.8+版本,部分語法在舊版本中可能不適用。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。