【Python3】列表字典集合元組
1 列表
1.1 定義與索引
在Python中,第一個列表元素的下標為 0通過將索引指定為 -1
可以讓Python返回最後一個列表元素
inventory = ['sword', 'armor', 'shield',
'big sword', 'big shiled'];
print(inventory[-1]);
1.2 修改 添加 刪除
1.2.1 修改元素
inventory = ['sword', 'armor', 'shield',
'big sword', 'big shield'];
inventory[-1] = 'small shield'
print(inventory)
'''
運行結果:
['sword', 'armor', 'shield', 'big sword', 'small shield']
'''
1.2.2 添加元素
- 在列表末尾添加元素
inventory1 = ['sword', 'armor', 'shield',
'big sword'];
inventory1.append('small shield');
print(inventory1)
#結果:['sword', 'armor', 'shield', 'big sword', 'small shield']
- 在列表中插入元素
inventory2 = ['armor', 'shield',
'big sword', 'small shield'];
inventory2.insert(0, 'sword');
print(inventory2)
#結果:['sword', 'armor', 'shield', 'big sword', 'small shield']
1.2.3 刪除元素
- 使用 del 語句刪除元素—–可以是任意位置
inventory = ['sword', 'armor', 'shield',
'big sword', 'big shield'];
del inventory[0];
print(inventory)
#結果:['armor', 'shield', 'big sword', 'small shield']
- 使用 pop( ) 刪除(彈出)元素—–可以是任意位置
inventory = ['sword', 'armor', 'shield',
'big sword', 'big shield'];
popped_inventory = inventory.pop(4);
print(inventory) #結果1
print(popped_inventory) #結果2
#結果1:['sword', 'armor', 'shield', 'big sword']
#結果2:small shield
- 使用 remove( ) 根據值刪除元素
inventory = ['sword', 'sword', 'armor', 'shield',
'big sword', 'big shield'];
inventory.remove('sword');
print(inventory);
#結果:['sword', 'armor', 'shield', 'big sword', 'small shield']
🎆注意:它只會刪除第一個指定的值
1.3 組織列表
1.3.1 使用 sort() 對列表進行 永久性 排列
mylist = ['sword', 'armor', 'big shield'];
mylist.sort();
print(mylist);
#結果1:['armor', 'big shield', 'sword']
mylist.sort(reverse = True);
print(mylist);
#結果2:['sword', 'big shield', 'armor']
1.3.2 使用 sorted() 對列表進行 臨時 排列
mylist = ['sword', 'armor', 'big shield'];
print(mylist); #結果1:['sword', 'armor', 'big shield'];
print(sorted(mylist)); #結果2:['armor', 'big shield', 'sword']
print(mylist); #結果3:['sword', 'armor', 'big shield'];
1.1.3 使用 reverse() 倒著列印列表
mylist = ['sword', 'armor', 'big shield'];
print(mylist.reverse());
#結果:['big shield', 'armor', 'sword']
1.1.4 使用 len() 確定列表的長度
mylist = ['sword', 'armor', 'big shield'];
len(mylist);
#結果:3
1.4 操作列表
1.4.1 for循環遍歷列表
magicians = ['alice', 'david', 'jack'];
for magician in magicians:
print(magician.title());
-------------------------------------------
Alice
David
Jack
1.4.2 避免縮進錯誤
- 忘記縮進或者忘記縮進額外的程式碼行
- 不必要的縮進(注意: 循環後的不必要的縮進)
- 遺漏了冒號
1.4.3 創建數字列表
1.4.3.1 使用函數 range()
print('...START...');
for value in range(1, 6): #Only 1 to 5
print('NO: ' + str(value));
print('...OVER...');
-------------------------------------------
...START...
NO: 1
NO: 2
NO: 3
NO: 4
NO: 5
...OVER...
1.4.3.2 創建數字列表
numbers = list(range(10, 1, -1));
numbers.append(1);
delete = numbers.pop(0);
print("...Erase " + str(delete) + '...');
print(numbers);
-------------------------------------------
...Erase 10...
[9, 8, 7, 6, 5, 4, 3, 2, 1]
1.4.3.3 簡單的統計計算
numbers = range(1, 5);
print('min: ');
print(min(numbers));
print('max: ');
print(max(numbers));
print('sum: ');
print(sum(numbers));
-------------------------------------------
min:
1
max:
4
sum:
10
1.4.3.4 列表推導式
squares = [value**2 for value in range(1, 11)]
print(squares);
-------------------------------------------
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1.4.4 使用列表的一部分
1.4.4.1 切片
my_food = ['pizza', 'falafel', 'carrot cake'];
friend_food = my_food[0:1];
#1 如果沒有指定起始索引,默認從開頭開始提取
#2 要讓切片終於末尾,類似 #1
print('My favorite foods are');
print(my_food);
print("\nMy friend's favorite foods are");
print(friend_food);
-------------------------------------------
My favorite foods are
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are
['pizza']
1.4.4.2 遍歷切片
foods = ['pizza', 'falafel', 'carrot cake'];
print('My favorite foods are');
for food in foods[:3]:
print(food.title());
-------------------------------------------
My favorite foods are
Pizza
Falafel
Carrot Cake
1.4.4.3 複製列表
my_food = ['pizza', 'falafel', 'carrot cake'];
friend_food = my_food[:];
print('My favorite foods are');
print(my_food);
print("\nMy friend's favorite foods are");
print(friend_food);
-------------------------------------------
My favorite foods are
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are
['pizza', 'falafel', 'carrot cake']
2 元組
列表非常適合用於存儲在程式運行期間可能變化的數據集
但有時需要一系列不可修改的元素, 元組可以滿足這種需求
2.1 定義元組
🍭使用圓括弧標識
foods = ('pizza', 'falafel', 'carrot cake');
print('My favorite foods are');
for food in foods[:3]:
print(food.title());
-------------------------------------------
My favorite foods are
Pizza
Falafel
Carrot Cake
2.2 修改元組變數
雖然不能元組的元素,但可以給存儲元組的變數賦值
foods = ('pizza', 'falafel', 'carrot cake');
print(foods);
foods = ('sword', 'shield', 'armor');
print(foods);
-------------------------------------------
('pizza', 'falafel', 'carrot cake')
('sword', 'shield', 'armor')
3 字典
3.1 定義與訪問
在Python中,字典 是一系列 鍵-值對。每個 鍵 都與一個 值 相關聯,可以使用鍵來訪問與之相關的值
與鍵相關聯的 值 可以是 數字,字元串,列表乃至字典
事實上,可將任何Python對象用作字典中的值,但鍵不行
fruit = {
'name': 'apple',
'color': 'red',
'quantity': 5
};
print(fruit['name']);
print(fruit['color']);
print(fruit['quantity']);
-------------------------------------------
apple
red
5
3.1.1 注意點
- 不允許同一個鍵出現兩次。創建時如果同一個鍵被賦值兩次,後一個會被記住
- 鍵必須不可變,所以可以用數字,字元串或元組充當,而用列表不行
3.2 修改 添加 刪除
3.2.1 修改字典中的值
apple = {'color': 'green'};
print('The apple is ' + apple['color'] + '.');
apple['color'] = 'red';
print('The apple is now ' + apple['color'] + '.');
-------------------------------------------
The apple is green.
The apple is now red.
3.2.2 添加 鍵-值對
fruit = {
'name': 'apple',
'color': 'red',
'quantity': 5
};
print(fruit);
fruit['x_position'] = 0;
fruit['y_position'] = 12;
print(fruit);
-------------------------------------------
{'name': 'apple', 'color': 'red', 'quantity': 5}
{'name': 'apple', 'color': 'red', 'quantity': 5, 'x_position': 0, 'y_position': 12}
3.2.3 刪除 鍵-值對
fruit = {
'name': 'apple',
'color': 'red',
'quantity': 5
};
print(fruit);
del fruit['quantity'];
print(fruit);
-------------------------------------------
{'name': 'apple', 'color': 'red', 'quantity': 5}
{'name': 'apple', 'color': 'red'}
3.3 遍歷字典
3.3.1 遍歷所有的鍵-值對
items()
people = {
'name': 'vivian',
'gender': 'man',
'hobby': 'python',
};
for key,value in people.items():
print(key.title() + ' : ' + value.title());
-------------------------------------------
Name : Vivian
Gender : Man
Hobby : Python
3.3.2 遍歷所有的鍵
keys()
people = {
'name': 'vivian',
'gender': 'man',
'hobby': 'python',
};
for key in people.keyes():
print(key.title());
-------------------------------------------
Name
Gender
Hobby
3.3.3 遍歷所有的值
people = {
'name': 'vivian',
'gender': 'man',
'hobby': 'python',
};
for value in people.values():
print(value.title());
-------------------------------------------
Vivian
Man
Python
3.4 字典內置函數&方法
3.4.1 Python字典包含的內置函數
people = {
'name': 'vivian',
'gender': 'man',
'hobby': 'python',
};
函數及描述 | 實例 |
---|---|
len(dict) 計算字典元素個數 |
>>>len(people) 3 |
str(dict) 輸出字典,可以列印的字元串表示 |
>>>str(people) {‘name’: ‘vivian’, ‘gender’: ‘man’, ‘interest’: ‘python’} |
type(variable) 返回變數類型 |
>>>type(people) <class ‘dict’> |
3.4.2 Python字典包含的內置方法
people = {
'name': 'vivian',
'gender': 'man',
'hobby': 'python',
};
函數與描述 | 實例 |
---|---|
dict.clear( ) | >>>people.clear(); >>>len(people); 0 |
dict.copy( ) | >>>person = people.copy(); >>>person {‘name’: ‘vivian’, ‘gender’: ‘man’, ‘hobby’: ‘python’} |
dict.fromkeys(seq[, value]) 中括弧內是選填 |
>>> seq = (‘name’,’sex’,’hobby’) >>> person = dict.fromkeys(seq) >>> person {‘name’: None, ‘sex’: None, ‘hobby’: None} >>> person = dict.fromkeys(seq,666) >>> person {‘name’: 666, ‘sex’: 666, ‘hobby’: 666} |
dict.get(key, default = None) | >>> people = { … ‘name’: ‘vivian’, … ‘gender’: ‘man’, … ‘hobby’: ‘python’, … }; >>> people.get(‘name’) ‘vivian’ >>> people.get(‘name’).title() ‘Vivian’ >>> people.get(‘nam’) #啥都沒有 |
dict.setdefault(key, defalut = None) 如果鍵不存在,將會添加鍵並將值設為默認值 |
>>> people.setdefault(‘nam’,None) >>> people.setdefault(‘name’,None) ‘vivian’ >>> people {‘name’: ‘vivian’, ‘gender’: ‘man’, ‘hobby’: ‘python’, ‘nam’: None} |
dict.update(dict2) 把 dict2 添加到指定字典 dict 中 |
>>> people.update({‘age’: 18}) >>> people {‘name’: ‘vivian’, ‘gender’: ‘man’, ‘hobby’: ‘python’, ‘nam’: None, ‘age’: 18} |
dict.pop(key[, defalut]) 中括弧內是選填 key:要刪除的鍵值 返回被刪除的值 |
>>> people.pop(‘name’) ‘vivian’ |
dict.popitem() 隨機返回並刪除字典中的最後一對鍵和值 如果字典已經為空,還使用它,則會報錯 |
>>> people.popitem(); (‘hobby’, ‘python’) >>> people.popitem(); (‘gender’, ‘man’) |
4 集合
4.1 定義
-
集合(set)是一個無序的不重複元素序列
-
可以使用大括弧 { } 或者 set() 函數創建集合
-
注意:創建一個空集合必須用 set() 而不是 { } ,因為 { } 是用來創建一個空字典
-
創建格式:
parame = {value01, value02......}
或者
set(value)
4.2 集合特性
>>> fruits = {'apple','orange','apple','pear','orange','banana'}
>>> print(fruits)
#去重功能
{'apple', 'banana', 'pear', 'orange'}
#判斷元素是否在集合內
>>> 'apple' in fruits
True
>>> 'onion' in fruits
False
#兩個集合之間的運算
>>> a = set('sgjahsgs')
>>> b = set('skajkshgs')
>>> a
{'s', 'g', 'j', 'a', 'h'}
>>> b
{'s', 'j', 'g', 'a', 'k', 'h'}
>>> b - a # b 比 a 多的部分
{'k'}
>>> a | b # 並集
{'s', 'g', 'j', 'a', 'k', 'h'}
>>> a & b # 交集
{'s', 'g', 'j', 'a', 'h'}
>>> a ^ b # 以它們並集為全集,兩者交集的補集
{'k'}
4.2.1 集合推導式
>>> a = {value for value in 'absjhagjgs' if value not in 'abc'}
>>> a
{'j', 'h', 's', 'g'}
4.3 添加 刪除
4.3.1 添加元素
>>> fruit = {'apple','banana','strawberry','onion'}
#1 使用add(element) 如果在集合中,element元素已經存在了,則不會進行任何操作
>>> fruit.add('grape')
#2 使用update(x)
#其參數可以是列表,元組,字典等
>>> fruit.update('h')
>>> fruit
{'onion', 'apple', 'grape', 'banana', 'h', 'strawberry'}
>>> fruit = {'apple','banana','strawberry','onion'}
>>> fruit.update([1,3])
>>> fruit
{1, 'onion', 3, 'apple', 'banana', 'strawberry'}
4.3.2 刪除元素
>>> fruit
{1, 'onion', 3, 'apple', 'banana', 'strawberry'}
>>> fruit.remove(1) #如果集合中不存在要移除的元素,則會發生錯誤
>>> fruit
{'onion', 3, 'apple', 'banana', 'strawberry'}
>>> fruit.discard(3) #如果集合中不存在要移除的元素,不會發生錯誤
>>> fruit
{'onion', 'apple', 'banana', 'strawberry'}
>>> fruit.pop() #隨機刪除,並返回被刪除的元素
'onion'
>>> fruit.pop()
'apple'
4.4 集合內置方法
>>> x = set('abcdf')
>>> y = set('abcrg')
>>> z = set('abczh')
>>> m = set('dhfjk')
函數與描述 | 實例 |
---|---|
set.difference(set) 返回集合的差集 |
>>> z = x.difference(y) >>> z {‘d’, ‘f’} |
set.difference_update(set) 移除兩個集合都包含的元素 無返回值 |
>>> x.difference_update(y) >>> x {‘f’, ‘d’} |
set.intersection(set1, set2 … etc) 返回集合的交集 |
>>> m = x.intersection(y, z) >>> m {‘c’, ‘b’, ‘a’} |
set.intersection_update(set1, set2 … etc) 無返回值 |
>>> x.intersection_update(y, z) >>> x {‘c’, ‘b’, ‘a’} |
isdisjoint() 判讀兩個集合是否包含相同元素 如果 沒有 返回True |
>>> x.isdisjoint(y) False |
set.issubset(set) 判斷是否是被包含 |
>>> x.issubset(y) True |
issuperset 判斷是否包含 |
>>> y.issuperset(x) True |
symmetric_difference() 返回交集在並集中的補集 |
>>> m = x.symmetric_difference(y) >>> m {‘g’, ‘r’} |
symmetric_difference_update() 無返回值 |
>>>x.symmetric_difference_update(y) >>> x {‘g’, ‘r’} |
union() 返回並集 |
>>> n = x.union(m) >>> n {‘f’, ‘b’, ‘d’, ‘h’, ‘k’, ‘a’, ‘c’, ‘j’} |