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'} |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/499696.html
標籤:Python
上一篇:web.xml檔案的功能簡介說明
下一篇:web.xml檔案的功能簡介說明
