上兩篇有關List的文章,此篇文上兩章的延續,整理一些常用的方法和操作。
[Python基礎]容器 list(列表),tuple(元組)
list
方法和操作,讓你能更靈活地處理列表數據enumerate()
for
迴圈中。my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
print(index, value)
# 輸出:
# 0 a
# 1 b
# 2 c
zip()
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped)) # 輸出: [(1, 'a'), (2, 'b'), (3, 'c')]
sum()
my_list = [1, 2, 3, 4]
total = sum(my_list)
print(total) # 輸出: 10
min()
和 max()
my_list = [1, 2, 3, 4]
print(min(my_list)) # 輸出: 1
print(max(my_list)) # 輸出: 4
all()
和 any()
all()
檢查列表中的所有元素是否都為True,any()
檢查列表中是否存在至少一個True。my_list = [True, True, False]
print(all(my_list)) # 輸出: False
print(any(my_list)) # 輸出: True
list comprehension
列表推導式my_list = [1, 2, 3, 4]
squares = [x**2 for x in my_list]
print(squares) # 輸出: [1, 4, 9, 16]
join()
my_list = ['Python', 'is', 'awesome']
sentence = ' '.join(my_list)
print(sentence) # 輸出: Python is awesome
len()
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # 輸出: 5
in
和 not in
my_list = [1, 2, 3]
print(2 in my_list) # 輸出: True
print(4 not in my_list) # 輸出: True
index(x[, start[, end]])
x
的索引,如果未找到則引發 ValueError
。可選參數 start
和 end
限制搜索範圍。my_list = [1, 2, 3, 4, 3]
index = my_list.index(3)
print(index) # 輸出: 2
count(x)
x
在列表中出現的次數。my_list = [1, 2, 3, 4, 3]
count = my_list.count(3)
print(count) # 輸出: 2
sort(key=None, reverse=False)
key
是一個函數,指定根據哪個條件排序。reverse=True
則從大到小排序。my_list = [4, 2, 3, 1]
my_list.sort()
print(my_list) # 輸出: [1, 2, 3, 4]
reverse()
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # 輸出: [4, 3, 2, 1]
copy()
my_list = [1, 2, 3]
new_list = my_list.copy()
print(new_list) # 輸出: [1, 2, 3]