數據類型是一類值,每個值都只屬于一種數據類型。變量不需要地顯式聲明數據類型,賦值時自動聲明。Python 有如下數據類型:
* 數字(Numbers)
* 字符串(String)
* 元組(Tuple)
* 列表(List)
* 字典(Dictionary)
* 集合(Set)
*****
[TOC]
*****
# 2.1 數字類型
在 Python 中,數字有四種類型。整型、浮點型、復數、布爾值。
```
int_num = 100 # 整型
float_num = 3.14 # 浮點型
complex_num = 3.0 + 3.5j # 復數
bool_ = True # 布爾值。True(非0)、False(0)。
```
```
# 復數 z = a + bj
# 實數部分:a。通過 z.real 獲取
# 虛數部分:b。通過 z.imag 獲取
# 虛數單位:j。
# a、b 均為實數。
```
**數字類型轉換**
int():將浮點型或純數字字符串或單個字母字符串('a'、'b' 等)轉換為整型,只保留整數部分。
```
>>> float_a = 3.6
>>> to_int_b = int(float_a)
3
>>> s = '1234'
>>> int(s)
1234
```
float():將整型或純數字字符串轉換為浮點型。
```
>>> int_a = 34
>>> float(int_a)
34.0
>>> st = '343'
>>> float(st)
343.0
```
complex():將整型或浮點型或純數字字符串轉換為復數
```
>>> int_a = 5
>>> complex(int_a)
(5+0j)
>>> s = '23'
>>> complex(s)
(23+0j)
```
complex(x, y):將 x 和 y 轉換到一個復數,實數部分為 x,虛數部分為 y。x 和 y 是數字表達式。
```
>>> complex(3.3,3.5)
(3.3+3.5j)
```
bool():將所給參數轉換為布爾型
```
>>> a = 156
>>> bool(a)
True
```
**算術操作符**
Python 操作符用來操作變量或常量值。
算術操作符用來進行數學運算。如下:
| 操作符 | 含義 | 示例 | 運算結果 |
| -- | -- | -- | -- |
| \*\* | 指數運算 | 2 ** 2 | 4 |
| % | 取模運算 | 11 % 3 | 2 |
| // | 整除運算 | 15 // 7 | 2 |
| / | 除法運算 | 12 / 5 | 2.4 |
| \* | 乘法運算 | 8 * 2 | 16 |
| - | 減法運算 | 2 - 1 | 1 |
| + | 加法運算 | 3 + 2 | 5 |
在 IDLE 中:
```
>>> 2 ** 2
4
>>> 18 % 4
2
>>> a = 15
>>> b = 3
>>> a / b
5.0
>>> 10 // -3
-4
>>> 11 / -4
-2.75
>>> -2 / 5
-0.4
```
**位操作符**
將數字以二進制進行運算。如下:
```
a = 60 # 二進制:0011 1100
b = 13 # 二進制:0000 1101
```
| 操作符 | 含義 | 示例 | 運算結果 |
| -- | -- | -- | -- |
| & | 按位與操作符:參與運算的兩個值,如果兩個相應位都為1,則該位的結果為1,否則為0。 | a & b | 12。二進制:0000 1100 |
| \| | 按位或操作符:只要對應的二個二進位有一個為1時,結果位就為1。 | a \| b | 61。二進制:0011 1101 |
| ^ | 按位異或操作符:當兩對應的二進位相異時,結果為1。 | a ^ b | 49。二進制:0011 0001 |
| ~ | 按位取反操作符:對數據的每個二進制位取反,即把1變為0,把0變為1。~x類似于-(x + 1) | ~a | -61。二進制:1100 0011 |
| << | 左移操作符:運算數的各二進位全部左移若干位,由"<<"右邊的數指定移動的位數,高位丟棄,低位補0。 | a << 2 | 240。二進制:1111 0000 |
| >> | 右移操作符:把">>"左邊的運算數的各二進位全部右移若干位,">>"右邊的數指定移動的位數。 | a >> 2 | 15。二進制:0000 1111 |
```
>>> a = 30
>>> ~a
-31
>>> a << 2
120
>>> a >> 2
7
```
> 參考學習:[二進制、八進制、十六進制與十進制互轉](https://linjianming.com/jinzhizhuanhuan.html)
**比較操作符**
對兩個對象進行比較,返回布爾值。假設 a=10,b=20
| 操作符 | 含義 | 示例 | 運算結果 |
| -- | -- | -- | -- |
| == | 等于-比較對象是否相等 | a == b | False |
| != | 不等于-比較兩個對象是否不相等 | a != b | True |
| > | 大于-判斷左邊對象是否大于右邊對象 | a > b | False |
| < | 小于-判斷左邊對象是否小于右邊對象 | a < b | True |
| >= | 大于等于-判斷左邊對象是否大于等于右邊對象 | a >= b | False |
| <= | 小于等于-判斷左邊對象是否小于等于右邊對象 | a <= b | True |
```
>>> a = 10
>>> b = 20
>>> a == b
False
>>> a < b
True
>>> a >= b
False
>>> a <= b
True
```
**賦值操作符**
假設a = 10,b = 20,c = 0:
| 操作符 | 含義 | 示例 | 運算結果 |
| -- | -- | -- | -- |
| = | 簡單的賦值操作符 | c = a + b - 將 a + b 的值賦值給 c | c = 30 |
| += | 加法賦值操作符 | c += a - 等效于 c = c + a | c = 10 |
| -= | 減法賦值操作符 | c -= a - 等效于 c = c - a | c = -10 |
| \*= | 乘法賦值操作符 | c \*= a - 等效于 c = c * a | c = 0 |
| /= | 除法賦值操作符 | c /= a - 等效于 c = c / a | c = 0.0 |
| %= | 取模賦值操作符 | c %= a - 等效于 c = c % a | c = 0 |
| \*\*= | 冪賦值操作符 | c \*\*= a - 等效于 c = c \*\* a | c = 0 |
| //= | 取整除賦值操作符 | c //= a - 等效于 c = c // a | c = 0 |
```
>>> a = 10
>>> b = 20
>>> c = 0
>>> c = a + b
>>> c
30
>>> c += a
>>> c
40
>>> c **= a
>>> c
10485760000000000
```
**邏輯操作符**
假設a = 10,b = 20:
| 操作符 | 邏輯表達式 | 含義 | 示例 | 運算結果 |
| -- | -- | -- | -- | -- |
| and | x and y | 布爾"與" - 如果 x 為 False,x and y 返回 False,否則它返回 y 的計算值。 | a and b | 20 |
| or | x or y | 布爾"或" - 如果 x 是 True,它返回 x 的值,否則它返回 y 的計算值。 | a or b | 10 |
| not | not x | 布爾"非" - 如果 x 為 True,返回 False 。如果 x 為 False,它返回 True。 | not a | False |
**身份操作符**
| 操作符 | 描述 | 實例 |
| --- | --- | --- |
| is | is 是判斷兩個標識符是不是引用自一個對象 | **x is y**, 類似**id(x) == id(y)**, 如果引用的是同一個對象則返回 True,否則返回 False |
| is not | is not 是判斷兩個標識符是不是引用自不同對象 | **x is not y**, 類似**id(a) != id(b)**。如果引用的不是同一個對象則返回結果 True,否則返回 False。 |
**注:** id()函數用于獲取對象內存地址。
```
>>> a = 20
>>> b = 20
>>> a is b
True
>>> id(a) == id(b)
True
```
```
>>> a = 2324
>>> b = 2324
>>> a is b
False
```
*注:* Python 中內建了 -5 到 256 這些對象,當我們重復使用這些數字時,使用的是同一個對象。
**內置函數**
abs(A):求A的絕對值
```
>>> a = -13
>>> abs(a)
13
```
divmod(A,B):除模操作,返回一個元組,形式為 (A/B, A%B)
```
>>> divmod(4, 3)
(1, 1)
```
pow(A, B):冪操作符,返回“A的B次方”
```
>>> pow(2, 2)
4
```
round(A):返回A的四舍五入結果
```
>>> round(5.4)
5
```
bin(A):將十進制A轉換為用二進制表示的字符
```
>>> bin(2)
'0b10'
```
oct(A):將十進制A轉換為用八進制表示的字符
```
>>> oct(8)
'0o10'
```
hex(A):將十進制A轉換為用十六進制表示的字符
```
>>> hex(16)
'0x10'
```
**相關模塊**
`math 模塊` [更詳細>>>](https://docs.python.org/zh-cn/3/library/math.html)
```
# 導入 math 模塊,查看包含的內容
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
```
ceil()
~~~
向上取整操作
格式:math.ceil(數值)
返回值:整型
~~~
```
>>> import math
>>> math.ceil(3.14)
4
```
floor()
~~~
向下取整操作
格式:math.floor(數值)
返回值:整型
~~~
```
>>> import math
>>> math.floor(3.66)
3
```
pow()
~~~
計算一個數值的N次方
格式: math.pow(底數,冪)
返回值:浮點類型 注意:該操作相當于**運算但是結果為浮點型
~~~
```
>>> import math
>>> math.pow(2,2)
4.0
```
sqrt()
~~~
開平方
格式:math.sqrt(數值)
返回值:浮點數
~~~
fabs()
~~~
對一個數值獲取其絕對值操作
格式:math.fabs(數值)
返回值:浮點數
~~~
abs()
~~~
對一個數值獲取其絕對值操作
格式:abs(數值)
返回值:可能是整數可以能浮點數
注意:abs() 他是內建函數 同時返回值根據原類型決定
~~~
modf()
~~~
將一個浮點數拆成整數和小數部分組成的元組
格式:math.modf(數值)
返回值:元組 (小數部分, 整數部分)
~~~
```
>>> import math
>>> math.modf(3.14159)
(0.14158999999999988, 3.0)
```
copysign()
~~~
將第二個數的正負號復制給第一個數
格式:math.copysign(值1,值2)
返回值:值1 符號是值2的正負號
~~~
```
>>> import math
>>> math.copysign(-2,6)
2.0
```
fsum()
~~~
將一個序列的數值進行相加求和
格式:math.fsum(序列)
返回值:浮點數
~~~
sum()
~~~
將一個序列的數值進行相加求和
格式:sum(序列)
返回值:數值類型
注意:此為 Python 內建函數
~~~
數學常量:
| 常量 | 描述 |
| --- | --- |
| pi | 數學常量 pi(圓周率,一般以π來表示) |
| e | 數學常量 e,e即自然常數。 |
```
>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
>>>
```
`random 模塊` [更詳細>>>](https://docs.python.org/zh-cn/3/library/random.html)
```
# random各種使用方法
import random
# 隨機生成[0.1)的浮點數
print("random():", random.random())
# 隨機生成1000-9999之間的整數
print("randint(1000, 9999):", random.randint(1000, 9999))
# 隨機生成0-20之間的偶數
print("randrange(0, 21, 2):", random.randrange(0, 21, 2))
# 隨機生成0-20之間的浮點數
print("uniform(0, 20):", random.uniform(0, 20))
# 從序列中隨機選擇一個元素
list_string = ['a', 'b', 'c', 'd', 'e']
print("choice(list):", random.choice(list_string))
print("choice(string):", random.choice('abcd'))
# 對列表元素隨機排序
list_number = [1, 2, 3, 4, 5]
random.shuffle(list_number)
print("shuffle(list):", list_number)
# 從指定序列中隨機獲取指定長度的片斷,返回列表
print("sample(sequence):", random.sample('abcdefg', 2))
```
*將上方 random 相關代碼保存到 random_test.py ,然后用終端運行,查看結果。*
*****
# 2.2 Sequence 類型
序列類型包括字符串(String)、元組(Tuple)、列表(List)。序列類型的元素有序排列,通過索引(下標)來訪問。
**索引/切片**
索引從左向右,從0開始;也可以從右向左,從\-1開始:

```
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
```
```
# 通過索引訪問序列元素
str1 = 'Hello Python'
print(sr1[4])
# 輸出:o
# 切片 str1[start:end] 取 如:str1[0:4],得到 'Hell'
print(str1[0:4])
# 輸出:Hell
# 切片 間隔取 str1[start:end:step] 如:str1[0:4:2],得到 'Hl' 即取索引 0 和 3 所對應元素。
print(str1[0:4:2])
# 輸出:Hl
# 輸出所有元素
print(str1[:])
# 輸出:Hello Python
# 逆序
print(str1[::-1])
```
**連接/相加:** seq1 + seq2。兩個序列類型一致才能相加。
```
>>> str1 = 'Hello '
>>> str2 = 'Python'
>>> str1 + str2
'Hello Python'
```
**重復/相乘:** seq1 * expr。將 seq1 重復 expr 次
```
>>> str1 = 'Python '
>>> str1 * 3
'Python Python Python '
```
**成員操作符**
| 操作符 | 描述 | 實例 |
| --- | --- | --- |
| in | 如果在指定的序列中找到值返回 True,否則返回 False。 | x 在 y 序列中 , 如果 x 在 y 序列中返回 True。 |
| not in | 如果在指定的序列中沒有找到值返回 True,否則返回 False。 | x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。 |
```
>>> str1 = 'abcdefghijklmnopqrstuvwxyz'
>>> 'a' in str1
True
>>> 1 not in str1
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
1 not in str1
TypeError: 'in <string>' requires string as left operand, not int
>>> '1' not in str1
True
```
*注:* 以上代碼出現了一個類型錯誤,提示我們操作符左側對象類型應該為字符串。
**其他操作符**
比較操作符。
```
>>> '22' > '23'
False
>>> [1,2,3] > [1,2,3,4]
False
>>> [4,5,6] > [1,2,3]
True
```
**內建函數**
序列類型間轉換:
str(A):將對象A轉換為字符型
```
>>> str(1)
'1'
>>> str([1,2,3,'ads',4.5])
"[1, 2, 3, 'ads', 4.5]"
```
tuple(A):將序列A轉換為元組
```
>>> tuple('abcdefg')
('a', 'b', 'c', 'd', 'e', 'f', 'g')
>>> tuple(1)
Traceback (most recent call last):
File "<pyshell#129>", line 1, in <module>
tuple(1)
TypeError: 'int' object is not iterable
```
list(A):將序列A轉換為列表
```
>>> list('Hello Python')
['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
```
len(A):求序列A長度
```
>>> str1 = 'Hello Python'
>>> len(str1)
12
```
其他:
all(seq) :如果序列的所有元素都為True,則返回True
```
>>> str1 = 'Hello Python'
>>> all(str1)
True
```
any(seq) :如果序列的任一元素為True,則返回True
```
>>> str2 = 'Welcom to Python'
>>> any(str2)
True
```
seq.count(subseq):返回子序列subseq在序列seq中出現的次數
seq.index(subseq):返回子序列subseq在序列seq中第一次出現下標
```
>>> str3 = 'Jack Lin is a handsome man!'
>>> str3.count('a')
4
>>> str3.index('a')
1
```
*參考Python文檔:*
當在序列中循環時,用 `enumerate()` 函數可以將索引位置和其對應的值同時取出
~~~
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
~~~
當同時在兩個或更多序列中循環時,可以用 `zip()` 函數將其內元素一一匹配。
~~~
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
~~~
*****
# 2.3 字符串
**字符串** 被標識為用引號表示的一組連續字符。Python 允許使用單引號或雙引號。字符串是不可變的序列數據類型,即每次對字符串進行任何更改時,都會創建全新的字符串對象。
```
a_str = 'Hello Python'
print(a_str) # 輸出整個字符串。Hello Python
print(a_str[0]) # 輸出字符串中第一個字符。H
print(a_str[0:5]) # 輸出字符串中前5個字符。Hello
```
> `a_str[i]` 表示通過索引(下標)獲取整個字符串中第i個字符。字符串中,第一個字符索引為0,從左向右索引依次增1
**獨特表示**
長字符串:用三引號(''' ''' 或 """ """)表示,可跨越多行、無需轉義,可包含單/雙引號。
原始字符串:r'' 。所有的字符串都是直接按照字面的意思來使用,沒有轉義特殊或不能打印的字符。 原始字符串除在字符串的第一個引號前加上字母r(可以大小寫)以外,與普通字符串有著幾乎完全相同的語法。
```
>>> print( r'\n' )
\n
>>> print( R'\n' )
\n
```
**eval()** 用來執行一個字符串表達式,并返回表達式的值。語法:
```
eval(expression[, globals[, locals]])
```
* expression -- 表達式。
* globals -- 變量作用域,全局命名空間,如果被提供,則必須是一個字典對象。
* locals -- 變量作用域,局部命名空間,如果被提供,可以是任何映射對象。
```
>>> str1 = '''Welcom to Python.'''
>>> str1 = '''Welcom to Python. '''
>>> x = 6
>>> eval('3 * x')
18
>>> eval('3 * 9')
27
>>> eval('pow(3,2)')
9
>>> eval('3 + 3')
6
>>> n = 108
>>> eval("n + 12")
120
```
**轉義字符**
在需要在字符中使用特殊字符時,python用反斜杠(\\)轉義字符,注意與原始字符串區別。如下表:
| 轉義字符 | 描述 |
| --- | --- |
| \\(在行尾時) | 續行符 |
| \\\\ | 反斜杠符號 |
| \\' | 單引號 |
| \\" | 雙引號 |
| \\a | 響鈴 |
| \\b | 退格(Backspace) |
| \\000 | 空 |
| \\n | 換行 |
| \\v | 縱向制表符 |
| \\t | 橫向制表符 |
| \\r | 回車 |
| \\f | 換頁 |
| \\oyy | 八進制數,yy代表字符,例如:\\o12代表換行 |
| \\xyy | 十六進制數,yy代表字符,例如:\\x0a代表換行 |
| \\other | 其它的字符以普通格式輸出 |
```
>>> print('Hello\n Python')
Hello
Python
```
**字符串格式化操作符:%**
按指定的規則連接、替換字符串并返回新的符合要求的字符串。如:
```
>>> print("我叫 %s 今年 %d 歲!" % ('小明', 10))
我叫 小明 今年 10 歲!
```
Python字符串格式化符號:
| ??? 符?? 號 | 描述 |
| --- | --- |
|%c | ?格式化字符及其ASCII碼 |
|%s | ?格式化字符串 |
|%d | ?格式化整數 |
|%u | ?格式化無符號整型 |
|%o | ?格式化無符號八進制數 |
|%x | ?格式化無符號十六進制數 |
|%X | ?格式化無符號十六進制數(大寫) |
|%f | ?格式化浮點數字,可指定小數點后的精度 |
|%F | ?與%f相似,但會將 `nan` 轉為 `NAN` 并將 `inf` 轉為 `INF`。 |
|%e | ?用科學計數法格式化浮點數 |
|%E | ?作用同%e,用科學計數法格式化浮點數 |
|%g | ?%f和%e的簡寫 |
|%G | ?%F和%E的簡寫 |
[更多 >>>](https://docs.python.org/zh-cn/3/library/string.html#format-specification-mini-language)
```
>>> charA = 65
>>> print('ASCII碼65代表:%c' % charA)
ASCII碼65代表:A
```
輔助格式化符號:
| 符號 | 功能 |
| --- | --- |
| \* | 定義寬度或者小數點精度 |
| \- | 用做左對齊 |
| + | 在正數前面顯示加號( + ) |
|\<sp\>| 在正數前面顯示空格 |
| # | 在八進制數前面顯示零('0'),在十六進制前面顯示'0x'或者'0X'(取決于用的是'x'還是'X') |
| 0 | 顯示的數字前面填充'0'而不是默認的空格 |
| % | '%%'輸出一個單一的'%' |
| (var) | 映射變量(字典參數) |
| m.n | m 是顯示的最小總寬度,n 是小數點后的位數(如果可用的話) |
```
>>> '%2d' % 3
' 3'
>>> '%#x' % 17
'0x11'
>>> '%3.3f' % 3
'3.000'
>>> '%3.1f' % 3
'3.0'
>>> '%5.1f' % 3
' 3.0'
>>> '% d' % 4
' 4'
```
**格式化字符串** `str.format()`
格式化字符串的函數str.format(),增強了字符串格式化的功能。
基本語法是通過{}和:來代替%。
format 函數可以接受不限個參數,位置可以不按順序。
| 數字 | 格式 | 輸出 | 描述 |
| --- | --- | --- | --- |
| 3.1415926 | {:.2f} | 3.14 | 保留小數點后兩位 |
| 3.1415926 | {:+.2f} | +3.14 | 帶符號保留小數點后兩位 |
| \-1 | {:+.2f} | \-1.00 | 帶符號保留小數點后兩位 |
| 2.71828 | {:.0f} | 3 | 不帶小數 |
| 5 | {:0>2d} | 05 | 數字補零 (填充左邊, 寬度為2) |
| 5 | {:x<4d} | 5xxx | 數字補x (填充右邊, 寬度為4) |
| 10 | {:x<4d} | 10xx | 數字補x (填充右邊, 寬度為4) |
| 1000000 | {:,} | 1,000,000 | 以逗號分隔的數字格式 |
| 0.25 | {:.2%} | 25.00% | 百分比格式 |
| 1000000000 | {:.2e} | 1.00e+09 | 指數記法 |
| 13 | {:10d} |13| 右對齊 (默認, 寬度為10) |
| 13 | {:<10d} |13| 左對齊 (寬度為10) |
| 13 | {:^10d} |13 | 中間對齊 (寬度為10) |
| 11 |{:b} | 1011 | 二進制|
```
>>> '{:.2f}'.format(3.1415926)
'3.14'
>>> '{:+.2f}'.format(3.1415926)
'+3.14'
>>> '{:+.2f}'.format(-1)
'-1.00'
>>> '{:.0f}'.format(2.71828)
'3'
>>> '{:0>2d}'.format(5)
'05'
>>> '{:x<4d}'.format(5)
'5xxx'
>>> '{:x<4d}'.format(10)
'10xx'
>>> '{:,}'.format(1000000)
'1,000,000'
>>> '{:.2%}'.format(0.25)
'25.00%'
>>> '{:.2e}'.format(1000000000)
'1.00e+09'
>>> '{:10d}'.format(13)
' 13'
>>> '{:<10d}'.format(13)
'13 '
>>> '{:>10d}'.format(13)
' 13'
>>> '{:^10d}'.format(13)
' 13 '
>>> '{:b}'.format(11)
'1011'
>>> '{:d}'.format(11)
'11'
>>> '{:o}'.format(11)
'13'
>>> '{:x}'.format(11)
'b'
>>> '{:#x}'.format(11)
'0xb'
>>> '{:#X}'.format(11)
'0XB'
```
`^`,`<`,`>`分別是居中、左對齊、右對齊,后面帶寬度,`:`號后面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。
`+`表示在正數前顯示+,負數前顯示\-;` `(空格)表示在正數前加空格
b、d、o、x 分別是二進制、十進制、八進制、十六進制。
按順序替換字符:
```
foo = 1
bar = 'bar'
baz = 3.14
print('{}, {} and {}'.format(foo, bar, baz))
# Out: "1, bar and 3.14"
```
按參數索引替換字符:
```
print('{0}, {1}, {2}, and {1}'.format(foo, bar, baz))
# Out: "1, bar, 3.14, and bar"
print('{0}, {1}, {2}, and {3}'.format(foo, bar, baz))
# Out: index out of range error
```
按參數名替換字符:
```
print("X value is: {x_val}. Y value is: {y_val}.".format(x_val=2, y_val=3))
# Out: "X value is: 2. Y value is: 3."
```
使用對象屬性:
```
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('My value is: {0.value}'.format(my_value)) # "0" is optional
# Out: "My value is: 6"
```
使用字典鍵:
```
my_dict = {'key': 6, 'other_key': 7}
print("My other key is: {0[other_key]}".format(my_dict)) # "0" is optional
# Out: "My other key is: 7"
```
列表、元組索引:
```
my_list = ['zero', 'one', 'two']
print("2nd element is: {0[2]}".format(my_list)) # "0" is optional
# Out: "2nd element is: two"
```
**內建函數**
* 適用標準序列類型的所有操作
* 常用操作
* 大小寫
* 合并/拼接
* 空白
* 更改顯示
* 寬度
* 編碼
* 檢查/查找
* 修改內容
常用操作:
```
str1 = 'Python is powerful and beautiful.'
```
—每個單詞首字母大寫:`str1.title()
`
```
>>> str1.title()
Python Is Powerful And Beautiful.'
```
—全部大寫/小寫:`str.upper()` / `str.lower()`
```
>>> str1.upper()
'PYTHON IS POWERFUL AND BEAUTIFUL.'
>>> str1.lower()
'python is powerful and beautiful.'
```
—首字母大寫,其余小寫:`str.capitalize()`
```
>>> 'it\'s a beautiful rabbit.'.capitalize()
"It's a beautiful rabbit."
```
—反轉大小寫:`str.swapcase()`
```
>>> 'it\'s a beautiful rabbit.'.swapcase()
"IT'S A BEAUTIFUL RABBIT."
```
—合并/拼接:`+` `%` `join(iterable)`
```
>>> str_a = 'Hello '
>>> str_b = 'Python'
>>> str_a + str_b
'Hello Python'
>>> s = '-'
>>> seq = ['h','e','l','l','o',' ','p','y','t','h','o','n']
>>> s.join(seq)
'h-e-l-l-o- -p-y-t-h-o-n'
```
—空白:添加空白: `\t` `\n` 刪除空白:兩端 `str.strip()` 開頭 `str.lstrip()` 末尾 `str.rstrip()`
```
>>> print('Hello\tPython')
Hello Python
>>> print('Hello\nPython')
Hello
Python
>>> st = ' It is a nice idea. '
>>> st.strip()
'It is a nice idea.'
>>> st.lstrip()
'It is a nice idea. '
>>> st.rstrip()
' It is a nice idea.'
```
更改顯示:
—寬度:
* str.center(width) 居中對齊,用空格填充
* str.ljust(width)/str.rjust(width) 左右對齊,用空格填充
* str.zfill(width) 用0填充
```
>>> str_s = 'python'
>>> str_s.center(12)
' python '
>>> str_s.ljust(12)
'python '
>>> str_s.rjust(12)
' python'
>>> str_s.zfill(12)
'000000python'
```
—編碼:
encode() 方法以指定的編碼格式編碼字符串。errors參數可以指定不同的錯誤處理方案。
encode()方法語法:
```
str.encode(encoding='utf-8',errors='strict')
```
參數:
* encoding -- 要使用的編碼,如: UTF-8。
* errors -- 設置不同錯誤的處理方案。默認為 'strict',意為編碼錯誤引起一個UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通過 codecs.register\_error() 注冊的任何值。
返回值:
該方法返回編碼后的字符串,它是一個 bytes 對象。
*---人為分割---*
decode() 方法以指定的編碼格式解碼 bytes 對象。默認編碼為 'utf-8'。
decode()方法語法:
```
bytes.decode(encoding="utf-8", errors="strict")
```
參數:
* encoding -- 要使用的編碼,如"UTF-8"。
* errors -- 設置不同錯誤的處理方案。默認為 'strict',意為編碼錯誤引起一個UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通過 codecs.register\_error() 注冊的任何值。
返回值:
該方法返回解碼后的字符串。
```
str = "隨心而碼"
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")
print(str)
print("UTF-8 編碼:", str_utf8)
print("GBK 編碼:", str_gbk)
print("UTF-8 解碼:", str_utf8.decode('UTF-8','strict'))
print("GBK 解碼:", str_gbk.decode('GBK','strict'))
```
輸出:
```
隨心而碼
UTF-8 編碼: b'\xe9\x9a\x8f\xe5\xbf\x83\xe8\x80\x8c\xe7\xa0\x81'
GBK 編碼: b'\xcb\xe6\xd0\xc4\xb6\xf8\xc2\xeb'
UTF-8 解碼: 隨心而碼
GBK 解碼: 隨心而碼
```
檢查/查找:
—count(str,beg=0,end=len(string)):返回str在string里面出現次數,可用開始索引(beg)和結束索引(end)指定搜索范圍
```
>>> m_str = 'hello python.hello good man.hello py.'
>>> s_str = 'hel'
>>> m_str.count(s_str)
3
```
—find(str,beg=0,end=len(string)):檢測str是否包含在string中,可用開始索引(beg)和結束索引(end)指定搜索范圍,找到返回索引,否則返回-1
—rfind(str,beg=0,end=len(string)):從右向左,檢測str是否包含在string中,可用開始索引(beg)和結束索引(end)指定搜索范圍 ,找到返回索引,否則返回-1
```
>>> m_str = 'hello python.hello good man.hello py.'
>>> s_str = 'goo'
>>> m_str.find(s_str)
19
>>> m_str.rfind(s_str)
19
```
—index(str,beg=0,end=len(string)):跟find()類似,但是如果str不在string中,則報異常
```
>>> m_str = 'hello python.hello good man.hello py.'
>>> s_str = 'py'
>>> m_str.index(s_str)
6
>>> ss_str = 'z'
>>> m_str.index(ss_str)
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
m_str.index(ss_str)
ValueError: substring not found
```
—endswith(obj,beg=0,end=len(string)):檢查字符串是否以 obj 結束,是則返回True,否則返回False,可用開始索引(beg)和結束索引(end)指定搜索范圍
```
>>> str1 = 'It is a good idea.'
>>> str1.endswith('.')
True
```
—startswith(obj,beg=0,end=len(string)):檢查字符串是否以 obj 開頭,是則返回True,否則返回False,可用開始索引(beg)和結束索引(end)指定搜索范圍
```
>>> str1 = 'It is a good idea.'
>>> str1.startswith('It')
True
```
—isalnum():如果字符串非空并且所有字符都是字母或數字,則返回True,否則返回False
```
>>> str1 = 'abcdefg'
>>> str1.isalnum()
True
>>> str2 = 'abcdef3456'
>>> str2.isalnum()
True
>>> str3 = '2345678'
>>> str3.isalnum()
True
>>> str4 = 'sdf@234'
>>> str4.isalnum()
False
```
—isalpha():如果字符串非空并且所有字符都是字母,則返回True,否則返回False
```
>>> 'abcdefghijk'.isalpha()
True
>>> '1234chg'.isalpha()
False
>>> ''.isalpha()
False
```
—isdigit():字符串為純數字字符,則返回True,否則返回False
```
>>> 'a'.isdigit()
False
>>> '234'.isdigit()
True
>>> '\t'.isdigit()
False
>>> r'\t'.isdigit()
False
>>> '\n'.isdigit()
False
>>> 'abcde'.isdigit()
False
```
—islower():如果字符串中的字符都是小寫,則返回True,否則返回False
```
>>> '12314'.islower()
False
>>> 'abcdefg'.islower()
True
>>> 'Abcdef'.islower()
False
>>> 'ASDFGH'.islower()
False
>>> '%@#$%'.islower()
False
```
—isspace():如果字符串是空格,則返回True,否則返回False
```
>>> ''.isspace()
False
>>> ' '.isspace()
True
>>> ' '.isspace()
True
```
—istitle():如果字符串中所有的單詞拼寫首字母為大寫,且其他字母為小寫,則返回 True,否則返回 False
```
>>> str_0 = 'This Is A Title.'
>>> str_0.istitle()
True
>>> str_1 = 'This is A Title.'
>>> str_1.istitle()
False
>>> str_2 = 'this is a title.'
>>> str_2.istitle()
False
```
—isupper():如果字符串中的字符都是大寫,則返回True,否則返回False
```
>>> str_case = 'IT IS A TITLE.'
>>> str_case.isupper()
True
>>> str_case_1 = 'iT IS A TITLE.'
>>> str_case_1.isupper()
False
>>> str_case_2 = 'it is a title.'
>>> str_case_2.isupper()
False
```
修改內容:
—expandtabs(tabsize=8):把字符串中的 tab 符號('\\t')轉為空格,tab 符號('\\t')默認的空格數是 8。該方法返回字符串中的 tab 符號('\\t')轉為空格后生成的新字符串
```
>>> str_ = 'I am so\thandsome!'
>>> print(str_.expandtabs())
I am so handsome!
>>> print(str_.expandtabs(16))
I am so handsome!
```
—replace(old,new,max):返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。
```
>>> str_ = 'hello world!'
>>> old = 'hello'
>>> new = 'hi'
>>> str_.replace(old,new)
'hi world!'
```
—split(str="", num=string.count(str))rsplit():split()通過指定分隔符 str 對字符串進行切片,如果參數 num 有指定值,則僅分隔 num+1 個子字符串,返回分割后的字符串列表
* str -- 分隔符,默認為所有的空字符,包括空格、換行(\\n)、制表符(\\t)等。
* num -- 分割次數。默認為 -1, 即分隔所有。
```
>>> str_sp = 'this is a beautiful place.'
>>> str_sp.split(' ')
['this', 'is', 'a', 'beautiful', 'place.']
>>> str_sp.split('i',3)
['th', 's ', 's a beaut', 'ful place.']
>>> str_sp.split('t',1)
['', 'his is a beautiful place.']
```
—rsplit():與 split() 類似,但 rsplit() 從右邊開始分割
```
>>> 'this is a beautiful girl.'.rsplit('i',1)
['this is a beautiful g', 'rl.']
```
—splitlines([keepends]):按照行('\\r', '\\r\\n', \\n')分隔,返回一個包含各行作為元素的列表。如果參數 keepends 為 False(默認),不包含換行符;如果為 True,則保留換行符
```
>>> 'this\n is\n\r a beaut\riful girl.'.splitlines()
['this', ' is', '', ' a beaut', 'iful girl.']
>>> 'this\n is\t\r a beaut\riful girl.'.splitlines(True)
['this\n', ' is\t\r', ' a beaut\r', 'iful girl.']
```
—partition(str)/rpartition(str):根據 str 分割字符串為三元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串。rpartition(str) 表示從右邊開始分割
```
>>> 'www.linjianming.com'.partition('.')
('www', '.', 'linjianming.com')
>>> 'www.linjianming.com'.rpartition('.')
('www.linjianming', '.', 'com')
```
****
# 2.4 元組
**元組** 是一種特殊的Sequence類型,用圓括號表示,不同元素之間用逗號隔開。元組的大小和其中的元素在初始化后*不可更改*。開發者定義了一個值的常量集,并且只需不斷連續讀取常量集,元組將發揮巨大作用。
```
>>> tupl = ()
>>> type(tupl)
<class 'tuple'>
>>> # 元組中只有一個元素時,應以逗號結尾
>>> tupl_1 = (12,)
>>> tupl_1
(12,)
>>> tupl_2 = (12,'23',124)
>>> tupl_2
(12, '23', 124)
```
**訪問元組元素** 通過下標索引訪問
```
>>> tup = (12,34,56,65)
>>> tup[0]
12
>>> tup[-1]
65
>>> tup[-2:]
(56, 65)
```
**修改元組元素將報錯**
```
>>> tup = (12,34,67,99,88,33,25)
>>> tup[1] = 43
Traceback (most recent call last):
File "<pyshell#73>", line 1, in <module>
tup[1] = 43
TypeError: 'tuple' object does not support item assignment
```
**可刪除整個元組** `del tuple`
```
>>> tup = ('12','hi',12)
>>> tup
('12', 'hi', 12)
>>> del tup
>>> tup
Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
tup
NameError: name 'tup' is not defined
```
刪除元組后再訪問元組,報錯提示元組未定義。
**適用于元組的操作符**
| Python 表達式 | 結果 | 描述 |
| --- | --- | --- |
| len((1, 2, 3)) | 3 | 計算元素個數 |
| (1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 連接 |
| ('Hi!',) \* 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | 復制 |
| 3 in (1, 2, 3) | True | 元素是否存在 |
| for x in (1, 2, 3): print (x,) | 1 2 3 | 迭代 |
**內置函數**
len(tuple) 計算元組元素個數。
```
>>> tuple1 = ('Google', 'Runoob', 'Taobao')
>>> len(tuple1)
3
```
max(tuple) 返回元組中元素最大值。
```
>>> tuple2 = ('5', '4', '8')
>>> max(tuple2)
'8'
```
min(tuple) 返回元組中元素最小值。
```
>>> tuple2 = ('5', '4', '8')
>>> min(tuple2)
'4'
```
tuple(seq) 將列表或字符串轉換為元組。
```
>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')
```
****
# 2.5 列表
**列表** Sequence類型之一,用中括號“[ ]” 表示,不同元素之間用逗號隔開。
*適用Sequence序列所有操作*
```
>>> # 定義
>>> lst = []
>>> lst
[]
>>> lst_1 = [12, 34, 'err']
>>> lst_1
[12, 34, 'err']
>>> # 索引與切片
>>> lst_2 = [12, 55, 'not', 'found', 404]
>>> lst_2[4]
404
>>> lst_2[1:3]
[55, 'not']
>>> lst_2[:-2]
[12, 55, 'not']
>>> # 修改列表元素
>>> lst_3 = ['it', 'is', 'so', 'good']
>>> lst_3[3] = 'cool'
>>> lst_3
['it', 'is', 'so', 'cool']
>>> # 獲取列表長度
>>> len(lst_3)
4
>>> # 刪除列表元素
>>> lst_4 = [12, 34, 56, 78, 89, 120]
>>> del lst_4[3]
>>> lst_4
[12, 34, 56, 89, 120]
>>> # 拼接
>>> lst_3 + lst_4
['it', 'is', 'so', 'cool', 12, 34, 56, 89, 120]
>>> # 重復
>>> lst_4 * 2
[12, 34, 56, 89, 120, 12, 34, 56, 89, 120]
```
**嵌套列表**
```
>>> lst_0 = [12, 34, 55, 66, 88]
>>> lst_1 = [99, 111, 133]
>>> lst = [lst_0, lst_1]
>>> lst
[[12, 34, 55, 66, 88], [99, 111, 133]]
>>> lst[0]
[12, 34, 55, 66, 88]
>>> lst[0][1]
34
```
**內置函數**
—append(obj):在列表末尾添加一個對象(元素)
```
>>> lst = ['你好', 'Python']
>>> lst.append('難學')
>>> lst
['你好', 'Python', '難學']
```
—insert(index,obj):把對象插入到index指定位置
```
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst.insert(1, 66)
>>> lst
[1, 66, 2, 3, 4, 5, 6, 7, 8, 9]
```
—extend(seq):把序列seq的內容添加到列表中
```
>>> lst = [11, 22, 33]
>>> str_ = 'it is so cool'
>>> lst.extend(str_)
>>> lst
[11, 22, 33, 'i', 't', ' ', 'i', 's', ' ', 's', 'o', ' ', 'c', 'o', 'o', 'l']
>>> tup = (77, 66, 55, 44, 33)
>>> lst.extend(tup)
>>> lst
[11, 22, 33, 'i', 't', ' ', 'i', 's', ' ', 's', 'o', ' ', 'c', 'o', 'o', 'l', 77, 66, 55, 44, 33]
```
—del:刪除列表元素
```
>>> lst = ['我', '愛', '她']
>>> del lst[1]
>>> lst
['我', '她']
>>> del lst
>>> lst
Traceback (most recent call last):
File "<pyshell#128>", line 1, in <module>
lst
NameError: name 'lst' is not defined
```
—pop(index=-1):讀取并刪除index(默認 -1,即末尾元素)位置的元素
```
>>> lst = [22, 33, 44, 55, 66, 77, 88, 99, 111, 222, 333]
>>> lst.pop()
333
>>> lst
[22, 33, 44, 55, 66, 77, 88, 99, 111, 222]
>>> lst.pop(4)
66
>>> lst
[22, 33, 44, 55, 77, 88, 99, 111, 222]
>>> lst.pop(-3)
99
>>> lst
[22, 33, 44, 55, 77, 88, 111, 222]
```
—remove(obj):刪除指定元素值obj。只刪除第一個匹配的obj
```
>>> lst = [22, 33, 44, 55, 77, 33, 88, 11, 22]
>>> lst.remove(22)
>>> lst
[33, 44, 55, 77, 33, 88, 11, 22]
```
—clear():清空列表
```
>>> lst = ['我', '愛', '她']
>>> lst.clear()
>>> lst
[]
```
—sort( key=None, reverse=False):對原列表進行排序,如果指定參數,則使用比較函數指定的比較函數。沒有返回值,但是會對列表的對象進行排序
* key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自于可迭代對象中,指定可迭代對象中的一個元素來進行排序。
* reverse -- 排序規則,reverse = True降序,reverse = False升序(默認)。
```
>>> lst = [1, 13, 24, 5, 10, 66, 35, 88, 2]
>>> lst.sort()
>>> lst
[1, 2, 5, 10, 13, 24, 35, 66, 88]
>>> lst.sort(reverse=True)
>>> lst
[88, 66, 35, 24, 13, 10, 5, 2, 1]
```
```
# 獲取列表的第二個元素
def takeSecond(elem):
return elem[1]
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# 指定第二個元素排序
random.sort(key=takeSecond)
# 輸出類別
print ('排序列表:', random)
# Out:排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]
```
—sorted()函數對所有可迭代的對象進行排序操作。
> **sort 與 sorted 區別:**
>
> sort 是應用在 list 上的方法,sorted 可以對所有可迭代的對象進行排序操作。
>
> list 的 sort 方法返回的是對已經存在的列表進行操作,而內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。
sorted 語法:
~~~
sorted(iterable, key=None, reverse=False)
~~~
參數說明:
* iterable -- 可迭代對象。
* key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自于可迭代對象中,指定可迭代對象中的一個元素來進行排序。
* reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(默認)。
返回值:返回重新排序的列表。
```
>>> lst = [3, 4, 1, 2, 6, 5, 9, 8, 7]
>>> sorted(lst)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst
[3, 4, 1, 2, 6, 5, 9, 8, 7]
>>> tup = (3, 5, 4, 2, 1)
>>> sorted(tup)
[1, 2, 3, 4, 5]
>>> dic = {1: 'D', 2: 'C', 3: 'B', 4: 'A'}
>>> sorted(dic)
[1, 2, 3, 4]
```
—reverse():獲得反向列表
```
>>> lst = ['我', '愛', '她']
>>> lst.reverse()
>>> lst
['她', '愛', '我']
```
—list(range(stop)):生成0-stop的數字,隔1,不包含stop
```
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
—列表解析:
```
>>> lst1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst2 = [i for i in lst1]
>>> lst2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
**列表推導式** *參考Python文檔*
> 列表推導式提供了一個更簡單的創建列表的方法。常見的用法是把某種操作應用于序列或可迭代對象的每個元素上,然后使用其結果來創建列表,或者通過滿足某些特定條件元素來創建子序列。 ——Python 文檔
例如,假設我們想創建一個平方列表,像這樣
~~~
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
~~~
注意這里創建(或被重寫)的名為`x`的變量在for循環后仍然存在。我們可以計算平方列表的值而不會產生任何副作用
~~~
squares = list(map(lambda x: x**2, range(10)))
~~~
或者,等價于
~~~
squares = [x**2 for x in range(10)]
~~~
上面這種寫法更加簡潔易讀。
列表推導式的結構是由一對方括號所包含的以下內容:一個表達式,后面跟一個`for`子句,然后是零個或多個`for`或`if`子句。 其結果將是一個新列表,由對表達式依據后面的`for`和`if`子句的內容進行求值計算而得出。 舉例來說,以下列表推導式會將兩個列表中不相等的元素組合起來:
~~~
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
~~~
而它等價于
~~~
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
~~~
注意在上面兩個代碼片段中,`for`?和`if`的順序是相同的。
如果表達式是一個元組(例如上面的`(x,y)`),那么就必須加上括號
~~~
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1, in <module>
[x, x**2 for x in range(6)]
^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
~~~
列表推導式可以使用復雜的表達式和嵌套函數
~~~
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
~~~
**列表作為棧使用** *參考Python文檔*
列表方法使得列表作為堆棧非常容易,最后一個插入,最先取出(“后進先出”)。要添加一個元素到堆棧的頂端,使用`append()`。要從堆棧頂部取出一個元素,使用`pop()`,不用指定索引。例如
~~~
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
~~~
**列表作為隊列使用** *參考Python文檔*
列表也可以用作隊列,其中先添加的元素被最先取出 (“先進先出”);然而列表用作這個目的相當低效。因為在列表的末尾添加和彈出元素非常快,但是在列表的開頭插入或彈出元素卻很慢 (因為所有的其他元素都必須移動一位)。
若要實現一個隊列,`collections.deque` 被設計用于快速地從兩端操作。例如
~~~
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
~~~
****
# 2.6 字典
字典是另一種可變容器模型,且可存儲任意類型對象。
字典的每個鍵值(key=>value)對用冒號( **:** )分割,每個對之間用逗號( **,** )分割,整個字典包括在花括號( **{}** )中 ,格式如下所示:
~~~
d = {key1 : value1, key2 : value2 }
~~~
鍵必須是唯一的,但值則不必。
值可以取任何數據類型,但鍵必須是不可變的,如字符串,數字或元組。
一個簡單的字典實例:
~~~
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
~~~
也可如此創建字典:
~~~
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
~~~
**訪問字典的值** 通過鍵訪問值
```
>>> dict1 = {1: 'Jack', 2: 'Joe', 3: 'Maria'}
>>> dict1[2]
'Joe'
```
訪問的不存在的鍵將出錯:
```
>>> dic = {1: 'Jack', 2: 'Joe', 3: 'Maria'}
>>> dic[4]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
dic[4]
KeyError: 4
```
**修改字典** 添加新的鍵值對,修改原有鍵值對
```
>>> dic = {'Name': 'Hicoder', 'Age': '24', 'College': 'Stanford University'}
>>> dic['Hobby'] = 'Basketball'
>>> dic
{'Name': 'Hicoder', 'Age': '24', 'College': 'Stanford University', 'Hobby': 'Basketball'}
>>> dic['Age'] = 18
>>> dic
{'Name': 'Hicoder', 'Age': 18, 'College': 'Stanford University', 'Hobby': 'Basketball'}
```
**刪除字典元素**
```
>>> dic = {'Name': 'Hicoder', 'Age': '24', 'College': 'Stanford University'}
>>> del dic['College']
>>> dic
{'Name': 'Hicoder', 'Age': '24'}
>>> del dic
>>> dic
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
dic
NameError: name 'dic' is not defined
```
**清空字典** dict.clear()
```
>>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'}
>>> dic.clear()
>>> dic
{}
```
**復制字典一個副本**
```
>>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'}
>>> dic_1 = dic.copy()
>>> dic_1
{'name': 'Adam', 'age': 18, 'hobby': 'running'}
```
**遍歷字典**
遍歷鍵值對:
```
>>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'}
>>> for k, v in dic.items(): \
print(k, v)
name Adam
age 18
hobby running
```
遍歷鍵:
```
>>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'}
>>> for k in dic: \
print('key:', k)
key: name
key: age
key: hobby
>>> for k in dic.keys(): \
print('key:', k)
key: name
key: age
key: hobby
```
遍歷值:
```
>>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'}
>>> for v in dic.values(): \
print('value:', v)
value: Adam
value: 18
value: running
```
**嵌套**
字典列表:在列表中嵌套字典,由多個字典組成的列表
```
>>> dic1 = {'name': 'Adam', 'age': 18, 'hobby': 'running'}
>>> dic2 = {'name': 'Jack', 'age': 19, 'hobby': 'basketball'}
>>> dic3 = {'name': 'Joe', 'age': 18, 'hobby': 'Pingpong'}
>>> student_info = [dic1, dic2, dic3]
>>> for std_info in student_info: \
print(std_info)
{'name': 'Adam', 'age': 18, 'hobby': 'running'}
{'name': 'Jack', 'age': 19, 'hobby': 'basketball'}
{'name': 'Joe', 'age': 18, 'hobby': 'Pingpong'}
```
(以下兩個例子摘自埃里克·瑪瑟斯《Python編程從入門到實踐》)
在字典中嵌套列表,適用于需要一個鍵關聯多個值時:
```
favorite_languages = {'Jen': ['Python', 'Ruby'], 'Sarah': ['C'], 'Edward': ['C++', 'JS']}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
```
```
# Out:
Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
Edward's favorite languages are:
C++
Js
```
字典嵌套字典:
```
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
```
```
# Out:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
```
****
# 2.7 集合
**集合**(set)是一個無序的不重復元素序列。
可以使用大括號{ }或者set()函數創建集合,注意:創建一個空集合必須用set()而不是{ },因為{ }是用來創建一個空字典。
```
>>> basket = {'banana', 'apple', 'orange', 'pear'}
>>> type(basket)
<class 'set'>
>>> set_chr = set('hello python')
>>> set_chr
{'p', 'o', ' ', 'n', 'l', 'h', 't', 'e', 'y'}
>>> # 剔除重復元素
>>> ball = {'basketball', 'football', 'table tennis', 'tennis', 'basketball', 'tennis'}
>>> ball
{'basketball', 'table tennis', 'tennis', 'football'}
```
**集合適用的操作符**
| 操作符 | 解釋 |
| -- | -- |
| in | 判斷包含關系 |
| not in | 判斷不包含關系 |
| ==、!=、>、<、>=、<=、 | 比較操作符 |
```
>>> sample1 = {1, 2, 3, 4, 5, 6, 7, 8}
>>> sample2 = {3, 2, 4, 5, 7, 9, 10}
>>> 6 in sample1
True
>>> 11 not in sample2
True
>>> sample1 >= sample2
False
```
**集合運算**
```
>>> a = set('abcdgklrt')
>>> b = set('abdkgehrkls')
>>> # 并集 OR
>>> a | b
{'b', 'l', 'e', 'r', 'd', 'a', 'g', 's', 'h', 'c', 'k', 't'}
>>> # 交集 AND
>>> a & b
{'b', 'd', 'g', 'k', 'l', 'r', 'a'}
>>> # 差集
>>> a - b
{'t', 'c'}
>>> # 對稱差分 XOR
>>> a ^ b
{'h', 's', 'c', 't', 'e'}
```
**內置函數**
添加元素:
```
>>> a_set = {5, 2, 0, 'Python', 'Lover'}
>>> # set.add(obj) 添加新元素
>>> a_set.add('China')
>>> a_set
{0, 'China', 2, 5, 'Python', 'Lover'}
>>> # set.update(seq) 用序列更新集合,序列的每個元素都被添加到集合中
>>> a_set.update('Ilove')
>>> a_set
{0, 'China', 2, 5, 'o', 'v', 'e', 'Python', 'Lover', 'I', 'l'}
```
刪除元素:
```
>>> b_set = {'I', 'Love', 'You', 'Python', 'China', 'Jane'}
>>> # set.remove(key):刪除指定的key
>>> b_set.remove('I')
>>> b_set
{'China', 'You', 'Jane', 'Python', 'Love'}
>>> b_set.remove('English')
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
b_set.remove('English')
KeyError: 'English'
>>> # set.discard(obj):若obj存在,則刪除它
>>> b_set.discard('World')
>>> b_set
{'China', 'You', 'Jane', 'Python', 'Love'}
>>> b_set.discard('You')
>>> b_set
{'China', 'Jane', 'Python', 'Love'}
>>> # set.pop():刪除任意一個元素
>>> b_set
{'China', 'Jane', 'Python', 'Love'}
>>> b_set.pop()
'China'
>>> b_set
{'Jane', 'Python', 'Love'}
```
****
# 2.8 操作符優先級
有括號,先括號。
| 操作符 | 描述 |
| --- | --- |
| \*\* | 指數 (最高優先級) |
| ~ + - | 按位翻轉, 一元加號和減號 (最后兩個的方法名為 +@ 和 -@) |
| \* / % // | 乘,除,取模和取整除 |
| \+ - | 加法減法 |
| \>> << | 右移,左移運算符 |
| & | 位 'AND' |
| ^ \| | 位運算符 |
| >= | 比較運算符 |
| <> == != | 等于運算符 |
| \= %= /= //= -= += \*= \*\*= | 賦值運算符 |
| is is not | 身份運算符 |
| in not in | 成員運算符 |
| and or not | 邏輯運算符 |