文/Bruce.Liu1
1.運算符
本章節主要說明Python的運算符。舉個簡單的例子 4 +5 = 9 。 例子中,4 和 5 被稱為操作數,"+" 稱為運算符。
Python語言支持以下類型的運算符:
- 算術運算符
- 比較(關系)運算符
- 賦值運算符
- 邏輯運算符
- 成員運算符
- 身份運算符
- 位運算符
- 運算符優先級
1.1.算術運算
- 以下假設變量: a=10,b=20:
以下運算結果是多少?
>>> 10 / 3 + 2.5
1.2.比較運算
- 以下假設變量: a=10,b=20:
Python 3以后丟棄<>方式
1.3.賦值運算
- 以下假設變量a為10,變量b為20:
1.4.邏輯運算
- Python語言支持邏輯運算符,以下假設變量 a 為 10, b為 20:
- or(或)示例
>>> a - b > 0 or b == a + 10
True
- and(與)示例
>>> a + 10 == b and b - a == 10
True
- not(非)示例
>>> a
10
>>> not a
False
1.5.成員運算
- 除了以上的一些運算符之外,Python還支持成員運算符,測試實例中包含了一系列的成員,包括字符串,列表或元組。
- 判斷成員是否在字符串、列表、元組中
>>> res_list = range(10)
>>> 5 in res_list
True
- 判斷成員是否不在字符串、列表、元組中
>>> test_code = 'Hello World'
>>> 'L' not in test_code
True
1.6.身份運算
- is示例驗證兩個標識符來自同一個引用
>>> def main():
... pass
...
>>> result = main()
>>> result is None
True
- 以下代碼和"sql result"做 == is運算返回是否相等
>>> a = 'sql result'
>>> a is 'sql result'
False
>>> a == 'sql result'
True
- is not 示例驗證兩個標識符來自不同引用
>>> a is not 'sql result'
True
1.7.位運算
- 按位運算符是把數字看作二進制來進行計算的。Python中的按位運算法則如下:
- 下表中變量 a 為 60,b 為 13,二進制格式如下:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
- 利用 bin() eval() int()方法,方便二、十進制的轉換
>>> a = 60
>>> binary_a = bin(a)
'0b111100'
>>> eval(binary_a)
60
>>> int(binary_a,2)
60
1.8.運算符優先級
- 以下表格列出了從最高到最低優先級的所有運算符:
簡單溫習一下小學數學
>>> a = 20
>>> b = 10
>>> c = 15
>>> d = 5
>>> e = 0
>>> e = (a + b) * c / d
>>> print "(a + b) * c / d 運算結果為:", e
(a + b) * c / d 運算結果為: 90
>>> e = ((a + b) * c) / d
>>> print "((a + b) * c) / d 運算結果為:", e
((a + b) * c) / d 運算結果為: 90
2.條件語句
Python條件語句是通過一條或多條語句的執行結果(True或者False)來決定執行的代碼塊。
可以通過下圖來簡單了解條件語句的執行過程:
2.1.用戶登錄驗證
2.1.1.基本控制子句
- 用戶輸入賬戶名和密碼,根絕輸入的對錯提示不同的消息
#!/bin/env python
#! _*_ coding:utf-8 _*_
import getpass
username = 'liu'
password = '745'
users = raw_input('Enter your name: ')
pwds = getpass.getpass('password : ')
if username == users and password == pwds :
print('Welcome user {_name}'.format(_name = users))
else:
print('invalid username or password!')
2.1.2.多重控制子句
2.1.2.1.多重控制子句-1
- 猜年齡程序,基于用戶輸入的年齡返回是否正確,及提示差距
問:當輸入18的時候,到底是返回那個結果?
#!/bin/env python
# _*_ coding:utf-8 _*_
__author__ = "Bruce"
age_of_python = 30
guess_age = raw_input('Enter age: ')
if guess_age < age_of_python:
print('think bigger!')
elif guess_age == 18:
print('成年了,騷年!')
elif guess_age > age_of_python:
print('think smaller!')
else:
print('yes. you got it.')
現實總是這么的讓人茫然,結果總是太出乎人的意料,think smaller!,python BUG?
# python 3_guess.py
Enter age: 18
think smaller!
2.1.2.1.多重控制子句-2
raw_input 函數接收的參數都將以str類型返回
input 函數將接收的參數數據類型原樣返回
3.x python 取消了input方法,raw_input方法改成成input()
- 此時在問:當輸入18的時候,到底是返回那個結果?
#!/bin/env python
# _*_ coding:utf-8 _*_
__author__ = "Bruce"
age_of_python = 30
#guess_age = input('Enter age: ')
guess_age = int(raw_input('Enter age: '))
if guess_age < age_of_python:
print('think bigger!')
elif guess_age == 18:
print('成年了,騷年!')
elif guess_age > age_of_python:
print('think smaller!')
else:
print('yes. you got it.')
3.循環語句
循環語句允許我們執行一個語句或語句組多次,下面是在大多數編程語言中的循環語句的一般形式:
- Python提供了for循環和while循環
- 循環控制語句可以更改語句執行的順序。Python支持以下循環控制語句:
3.1.loop循環
3.1.1.簡單的Loop循環
>>> for i in range(10):
... print 'Loop:',i
...
Loop: 0
Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
Loop: 6
Loop: 7
Loop: 8
Loop: 9
3.1.2.循環控制語句
循環控制語句可以更改語句執行的順序
3.1.2.1.循環控制語句continue
continue子句的作用:停止并跳出當前本次循環,執行下一次循環
打印1到100數字,打印到50的時候顯示特殊信息
>>> for i in range(100):
... if i == 50:
... print 'I have got to the round 50th!'
... continue
... print i
3.1.2.2.循環控制語句break
break子句的作用:終止循環,并跳出整個循環體
打印1到100數字,打印到50的時候顯示信息并停止程序
>>> for i in range(100):
... if i == 50:
... print 'I have got to the round 50th!'
... break
... print i
3.1.2.3.循環控制語句pass
僅僅是為了是代碼保持語法完整性的.
該代碼,竟不能夠執行,因為python認為有從屬關系的代碼塊,就必須有子代碼
>>> for i in range(10):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
改成這種方法即可。這會非常有用。
>>> for i in range(10):
... pass
...
3.2.while 循環
3.2.1.無限循環
# !/bin/env python
count = 0
while True:
print 'loop:',count
count +=1
3.2.2.條件循環
打印1到100數字,打印到50的時候顯示特殊信息,打印到70停止程序
#!/bin/env python
# _*_ coding:utf-8 _*_
__author__ = "Bruce"
counter = 1
while True:
counter += 1
if counter == 50:
print 'I have got to the round 50th!'
continue
elif counter > 70:
break
print counter
3.3.嵌套循環
- 九九乘法表
>>> for i in range(1,10):
... for j in range(1,10):
... print "{} x {} = {}".format(i, j, i * j)
4.字符串操作
字符串是 Python 中最常用的數據類型。我們可以使用引號('或")來創建字符串。和其他語言一樣字符串是不可修改的。
4.1.字符串基本操作
4.1.1.聲明字符串
創建字符串很簡單,只要為變量分配一個值即可。例如:
>>> msg = 'Hello World'
4.1.2.單引號、雙引號
python中沒有字符串的引用符 雙引號 " 、單引號'。沒有強引用、弱引用之說,有些情況確需要不懂的引用方式
示例一
>>> 'hello,world!'
'hello,world!'
示例二 這種方式明顯是語法錯誤。如何表示我們想要表達的意思呢?
>>> 'Let's go!'
File "<stdin>", line 1
'Let's go!'
^
SyntaxError: invalid syntax
示例三 通過雙引號表示
>>> "Let's go!"
"Let's go!"
示例四 或者通過轉移符 \將 Let's轉轉成普通字符
>>> 'Let\'s go!'
"Let's go!"
4.1.3.字符串拼接
>>> x= 'Hello,'
>>> y = 'world!'
>>> x + y
'Hello,world!'
4.1.4.訪問字符串的值
Python訪問子字符串,可以使用方括號來截取字符串,如下實例:
- 默認(下標0開始);[0:5]表示從下標0開始匹配,匹配到5結束,這種方式也叫切片。(切片search數據的方式是:顧頭不顧尾)
>>> msg = 'Hello World'
>>> msg[0]
'H'
>>> msg[0:5]
'Hello'
4.2.轉義字符
4.3.字符串運算符
4.5.字符串格式化
4.6.字符串內置方法
字符串方法是從python1.6到2.0慢慢加進來的——它們也被加到了Jython中。
這些方法實現了string模塊的大部分方法,如下表所示列出了目前字符串內建支持的方法,所有的方法都包含了對Unicode的支持,有一些甚至是專門用于Unicode的。
- 獲取幫助信息
help的時候方法不需要加括號
>>> msg = 'hello world'
>>> help(msg.capitalize)
- 首字母大寫
>>> msg.capitalize()
'Hello world'
- 集中對齊
>>> msg.center(15 )
' hello world '
>>> msg.center(15 ,'#')
'##hello world##'
- 統計輸入參數出現的次數
>>> msg.count('l')
3
- 編碼成bytes格式
>>> msg.encode()
'hello world'
- 判斷字符串結尾是否包含輸入參數
>>> msg.endswith('world')
True
- 自動以制表符的長度
>>> text = 'hello\tworld'
>>> print text
hello world
>>> text.expandtabs(10)
'hello world'
- 返回字符串位置,沒有則返回-1(默認下標0開始自左向右find,找到就返回)
>>> msg.find('l')
2
>>> msg.find('x')
-1
- 格式化字符串
第一種寫法
>>> cmd = "mysql -h{ip} -P{port} -u{user} -p{passs}".format(ip='localhost',port=3306,user='mysql',passs='buzhidao')
>>> cmd
'mysql -hlocalhost -P3306 -umysql -pbuzhidao'
第二種寫法
>>> cmd = "mysql -h{0} -P{1} -u{2} -p{3}".format('localhost',3306,'mysql','buzhidao')
>>> print cmd
mysql -hlocalhost -P3306 -umysql -pbuzhidao
第三種寫法
>>> cmd = "mysql -h{} -P{} -u{} -p{}".format('localhost',3306,'mysql','buzhidao')
>>> cmd
'mysql -hlocalhost -P3306 -umysql -pbuzhidao'
- 返回字符串位置,沒有則報錯(多個重復值時,找到第一個就返回)
>>> msg.index('l')
2
>>> msg.index('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
- 判斷是否是標準字符(0-9,a-Z)
>>> msg.isalnum()
False
>>> '09aZ'.isalnum()
True
- 判斷是否是字母(a-Z)
>>> 'asdf'.isalpha()
True
>>> 'as21'.isalpha()
False
- 判斷是否是數字(0-9)
>>> '123'.isdigit()
True
- 判斷是否是小寫
>>> msg.islower()
True
- 判斷是否是空格
>>> s = ' '
>>> s.isspace()
True
- 判斷是否是首字母大寫
>>> _msg = 'Hello World'
>>> _msg.istitle()
True
- 判斷字符串是否全部是大寫
>>> _msg = 'TEST CODE'
>>> _msg.isupper()
- 將序列中的元素以指定的字符連接生成一個新的字符串
>>> tuple_res = ('Bruce','BJ')
>>> '#'.join(tuple_res)
'Bruce#BJ'
- 顯示長度,不夠時右邊用空格填充
>>> msg.ljust(12)
'hello world '
- 返回字符串小寫格式
>>> _msg.lower()
'test'
- 去掉左邊的空格回車符
>>> text = '\n\taa'
>>> print text
aa
>>> text.lstrip()
'aa'
- 默認從左側開始匹配;返回一個3元的元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串
>>> names = 'Burce.Liu'
>>> names.partition('.')
('Burce', '.', 'Liu')
- 字符串替換,默認全面替換
>>> info = '***** hotle'
>>> hotel = info.replace('*','星')
>>> print hotel
星星星星星 hotle
- 返回字符串位置,沒有則返回-1
默認(下標0開始) 自左向右find,找到最右側的在返回
>>> msg
'hello world'
>>> msg.rfind('l')
9
>>> msg.find('a')
-1
- 從右至左返回字符串位置,沒有則報錯(多個重復值時,找到第一個就返回)
>>> msg.rindex('l')
9
- 顯示長度,不夠時左邊用空格填充
>>> msg.rjust(12)
' hello world'
- 從右邊開始切分,返回一個3元的元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串
>>> url = 'www.hanxiang.com'
>>> url.rpartition('.')
('www.hanxiang', '.', 'com')
- 從右側開始,將字符串默認以空格分割,分割后以list的形勢返回
>>> msg.rsplit()
['hello', 'world.', 'none..']
- 去掉右邊的空格回車符
>>> test = '\n\ttile......\n\t'
>>> print test.rstrip()
tile......
- 將字符串默認以空格分割,分割后以list的形勢返回
>>> names.split('.')
['Burce', 'Liu']
- 按照行('\r', '\r\n', \n')分隔,返回一個包含各行作為元素的列表
>>> info = '123\n456\n789'
>>> info.splitlines()
['123', '456', '789']
- 判斷字符串首部是否包含參數值
>>> ftp_cmd = 'get file'
>>> ftp_cmd.startswith('get')
True
- 默認脫掉兩邊的空格回車符
>>> test = '\n\ttile......\n\t'
>>> print test
tile......
>>> test.strip()
'tile......'
- 對字符串的大小寫字母進行轉換
>>> info = 'Test Code!'
>>> info.swapcase()
'tEST cODE!'
- 返回字符串首字母大寫
>>> msg.title()
'Hello World. None..'
- 方法根據參數table給出的表(包含 256 個字符)轉換字符串的字符
>>> from string import maketrans
>>> intab = 'a'
>>> outtab = '1'
>>> # str.translate(table[, deletechars]);
>>> # table -- 翻譯表,翻譯表是通過maketrans方法轉換而來。
>>> # deletechars -- 字符串中要過濾的字符列表。
>>> trantab = maketrans(intab, outtab)
>>> str = "a this is string example....wow!!!";
>>> print str.translate(trantab)
1 this is string ex1mple....wow!!!
- 返回字符串的大寫形式
>>> msg.upper()
'HELLO WORLD. NONE..'
- 方法返回指定長度的字符串,原字符串右對齊,前面填充0。
>>> #返回一個值的ASCII映射值
>>> ord('2')
50
>>> #將50轉換成二進制方式表示
>>> bin(ord('2'))
'0b110010'
>>> #用zfill方法填充默認不夠的0
>>> binary_num.zfill(10)
'000b110010'
4.7.字符串的進階
- 返回變量的類型
>>> type(msg)
<type 'str'>
- 返回最大值
>>> msg = 'my name is Burce1.'
>>> max(msg)
'y'
- 返回最小值
>>> min(msg)
' '
- 取長度
>>> len(msg)
18
- 數據類型轉換-int
>>> one = '1'
>>> num1 = int(one)
>>> type(num1)
<type 'int'>
- 數據類型轉換-str
>>> numtwo = str(num1)
>>> type(numtwo)
<type 'str'>
- ascii轉換-1(str -> ascii)
>>> ord('a')
97
- ascii轉換-2(ascii -> str)
>>> chr(97)
'a'
- 比較兩個值的大小
>>> a = 'z'
>>> b = 'a'
>>> cmp(a,b)
1
>>> cmp(b,a)
-1
- 為每一個元素添加一個ID
>>> import string
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> for i in string.lowercase:
... print string.lowercase.index(i),i
...
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
12 m
13 n
14 o
15 p
16 q
17 r
18 s
19 t
20 u
21 v
22 w
23 x
24 y
25 z
- 想合并一組序列如何做
>>> nums = ('Bruce',27,'erha',1,'QQ',23)
>>> ','.join(nums)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected string, int found
嘗試一下代碼
>>> nums = ('Bruce',27,'erha',1,'QQ',25)
>>> result = ''
>>> for i in nums:
... if type(i) is int:
... result += '{},'.format(str(i))
... continue
... result += '{},'.format(i)
...
>>> result
'Bruce,27,erha,1,QQ,25,'
5.列表操作
列表是最常用的Python數據類型,它可以作為一個方括號內的逗號分隔值出現。并且列表內的數據類型靈活多變。
列表(list)具有一下幾個特點:
- 任意對象的有序集合
- 可變的序列
有一個需求需要存放班級所有同學的姓名,如果有同學休學或其他原因造成不能繼續上課,存放數據的結構中還需要對應的維護,如何存放數據呢?
- 這種寫法顯然不能靈活的維護更新數據,那么此時就引入了list數據類型
>>> grade = 'erha,eric,Bruce,tom'
其實通過剛才的知識就能將字符串轉換成list,那么此時grade_list就變得很好維護更新了
>>> grade_list = grade.split(',')
>>> grade_list
['erha', 'eric', 'Bruce', 'tom']
5.1.列表的基本操作
5.1.1.定義列表
name_list = ['Bruce','erha','tom','Yang']
5.1.2.訪問列表
- 獲取list元素,默認下標0是第1個位置,以此類推
>>> name_list[0]
'Bruce'
>>> name_list[-1]
'Yang'
5.1.3.切片
如果說想一次性訪問list中多個元素如何做呢?
- 取下標1~4的元素(包括1,不包括4)
>>> names = ['Bruce','tom','jack','Yang','QQ']
>>> names[1:4]
['tom', 'jack', 'Yang']
- 取下標2~-1的元素(-1是元素中最右側的下標)
>>> names[2:-1]
['jack', 'Yang']
- 從頭開始取,取到下標3
>>> names[:3]
['Bruce', 'tom', 'jack']
>>> names[0:3]
['Bruce', 'tom', 'jack']
- 去最后3下標的元素
>>> names[-3:]
['jack', 'Yang', 'QQ']
#這種是錯誤的,因為-1在尾部不能被包含
>>> names[-3:-1]
['jack', 'Yang']
- 取下標3之前的元素,每隔一個元素,取一個
>>> names[:3:2]
['Bruce', 'jack']
- 也可以基于切片,指定下標2位置插入
>>> names[2:2] = ['wang da chui']
>>> names
['Bruce', 'tom', 'wang da chui', 'jack', 'Yang', 'QQ']
5.2.列表的內置方法
- 列表末尾追加元素
>>> names = ['Bruce', 'tom', 'wang da chui', 'jack', 'Yang', 'QQ']
>>> names.append('QQ')
- 統計元素在列表中出現的個數
>>> names.count('QQ')
2
- 擴展列表
>>> names = ['Bruce', 'tom', 'wang da chui', 'jack', 'Yang', 'QQ']
>>> names.extend(range(10))
>>> print names
等于以下方式
>>> names += range(10)
>>> print names
- 返回該元素的位置,無則拋異常,并且匹配第一個元素即返回
>>> names.index('QQ')
5
>>> names.index('Tom')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list
- 指定元素下標插入
>>> names.insert(4,'新來的')
>>> print names[4]
新來的
- 指定下標刪除元素并返回刪除的元素,默認不指定刪除最后一個元素
>>> names.pop(4)
'\xe6\x96\xb0\xe6\x9d\xa5\xe7\x9a\x84'
>>> names.pop()
4
- 刪除第一次出現的改元素
>>> names.remove('QQ')
- 倒序
>>> names.reverse()
>>> names
[3, 2, 1, 0, 'QQ', 'Yang', 'jack', 'wang da chui', 'tom', 'Bruce']
- 排序
>>> names.sort()
>>> names
[0, 1, 2, 3, 'Bruce', 'QQ', 'Yang', 'jack', 'tom', 'wang da chui']
倒序、排序都是基于首字符ascii碼的大小進行的
5.3.列表的高級進階
5.3.1.Enumerate枚舉
enumerate在循環的同時直接訪問當前的索引值
>>> for k, v in enumerate(names):
... print k, v
...
0 0
1 1
2 2
3 3
4 Bruce
5 QQ
6 Yang
7 jack
8 tom
9 wang da chui
5.3.2.找出列表中的最大值
>>> import random #隨機模塊,后面展開講解
>>>
>>> sequences = range(15)
>>> random.shuffle(sequences)
>>> d = -1
>>> for i in sequences:
... if i > d:
... d = i
...
>>> print d
14
5.3.3.列表的復制
5.3.3.1.潛復制
- 一維數據潛復制驗證,
>>> import copy
>>> names = ['Bruce', 'Eric', 'goods cat!']
>>> names2 =copy.copy(names)
>>> names[1] = 'eric'
>>> print names
['Bruce', 'eric', 'goods cat!']
>>> print names2
['Bruce', 'Eric', 'goods cat!']
- 二維數據或多維數據中潛復制的區別
但是二維列表中發現,其實淺復制并沒有真正的復制一個單獨的列表,而是指向了同一個列表的指針,這就是潛復制;二維數據時,潛復制并不會完全的復制一個副本
>>> shopping = [['Iphone',5800],['Nike',699],'buy']
>>> copy_shopping = copy.copy(shopping)
>>> shopping[0][0]
'Iphone'
>>> shopping[0][1] = 5699
>>> print shopping
[['Iphone', 5699], ['Nike', 699], 'buy']
>>> print copy_shopping
[['Iphone', 5699], ['Nike', 699], 'buy']
- 潛復制也并非雞肋,我們看一場景:
父子卡賬戶擁有相同的一個卡號和金額,但是名字不同,發生扣款時金額必須同時扣款
>>> blank_user = ['names',['blank_name','card_type',0]]
>>> Tom = ['犀利哥',['光大','儲值卡',800]]
>>> jery = copy.copy(Tom)
>>> jery[0] = '鳳姐'
>>> jery[1][2] = 800 - 699
>>> print jery[0],jery[1][2]
鳳姐 101
>>> print Tom[0],Tom[1][2]
犀利哥 101
5.3.3.2.深復制
- 深復制才是真正的將多維元素進行完全的copy(類似于軟連接、硬鏈接)
>>> shopping = [['Iphone',5800],['Nike',699],'buy']
>>> deepcopy_shopping = copy.deepcopy(shopping)
>>> shopping[0] = ['Iphone Plus','8800']
>>> shopping
[['Iphone Plus', '8800'], ['Nike', 699], 'buy']
>>> deepcopy_shopping
[['Iphone', 5800], ['Nike', 699], 'buy']
5.3.4.列表的轉換
- str轉換list
>>> import string
>>> result = string.uppercase
>>> list_res = list(result)
>>> print list_res
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
- list轉換str
str方法僅僅是將數據結構外面用引號,這并不是我們想要的結果
>>> str(list_res)
"['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']"
- 正確的姿勢
>>> ''.join(list_res)
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
補充
- zip拉鏈
兩個列表長度不一致,zip拉鏈的時候,自動截取一致
>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8, 9]
>>> zip(a,b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
兩遍元數量一樣的效果
>>> a.append('new')
>>> zip(a,b)
[(1, 5), (2, 6), (3, 7), (4, 8), ('new', 9)]
- map方法
如果list長度不一致,則用None補充
>>> b.append(10)
>>> map(None,a,b)
[(1, 5), (2, 6), (3, 7), (4, 8), ('new', 9), (None, 10)]
6.元組操作
元組:tuple。tuple和list非常類似,但是tuple一旦初始化就不能修改,比如同樣是列出同學的名字、函數或其他對象的返回結果都是元組形式
元組(tuple)具有以下幾個特點:
- 任意對象的有序集合
- 不可變的序列
6.1.元組的基本操作
6.1.1.聲明一個元組
>>> db_res = ('as','the','is','at','go')
6.1.2.訪問元組
>>> db_res[0]
'as'
因為元組是只讀的所以沒有過多關于修改的內置函數,也不支持修改元組中的元素
>>> db_res[0] = 'Change'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
6.2.元組的內置方法
- 統計元素出現的次數
>>> db_res.count('as')
1
- 返回元素的下標位置
>>> db_res.index('at')
3
補充
- tuple -> list
>>> list_db_res = list(db_res)
>>> print list_db_res
['as', 'the', 'is', 'at', 'go']
- list -> tuple
>>> db_res_2 = tuple(list_db_res)
>>> print db_res_2
('as', 'the', 'is', 'at', 'go')
- tuple -> str
result_tuple = ('Tablespace->', 'INDEX_PAY', 'TotalSize->', 69632, 'FreeSize->', 14293.0625, 'UsedSize->', 55338.9375, 'FreePencent->', 20.52)
>>> tmp_res = ''
>>> for i in result_tuple:
... tmp_res += str(i)
>>> print tmp_res
Tablespace->INDEX_PAYTotalSize->69632FreeSize->14293.0625UsedSize->55338.9375FreePencent->20.52
7.字典操作
Python內置了字典:dict的支持,dict全稱dictionary,在其他語言中也稱為map,使用鍵-值(key-value)存儲,具有極快的查找速度。
字典(dict)具有以下幾個特點:
- 任意對象的無序集合
- 可變的序列
- Search元素效率極高
為什么dict查找速度這么快?因為dict的實現原理和查字典是一樣的。假設字典包含了1萬個漢字,我們要查某一個字,一個辦法是把字典從第一頁往后翻,直到找到我們想要的字為止,這種方法就是在list中查找元素的方法,list越大,查找越慢。
第二種方法是先在字典的索引表里(比如部首表)查這個字對應的頁碼,然后直接翻到該頁,找到這個字,無論找哪個字,這種查找速度都非常快,不會隨著字典大小的增加而變慢。
dict就是第二種實現方式,給定一個名字,比如'Michael',dict在內部就可以直接計算出Michael對應的存放成績的“頁碼”,也就是95這個數字存放的內存地址,直接取出來,所以速度非常快。
你可以猜到,這種key-value存儲方式,在放進去的時候,必須根據key算出value的存放位置,這樣,取的時候才能根據key直接拿到value。
- 假設要根據同學的名字查找對應的成績,如果用list實現,需要兩個list
給定一個名字,要查找對應的成績,就先要在names中找到對應的位置,再從scores取出對應的成績,list越長,耗時越長。
>>> names = ['Michael', 'Bob', 'Tracy']
>>> scores = [95, 75, 85]
- 如果用dict實現,只需要一個“名字”-“成績”的對照表,直接根據名字查找成績,無論這個表有多大,查找速度都不會變慢。用Python寫一個dict如下:
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
7.1.字典的基本操作
7.1.1.聲明一個字典
- 如創建一個員工信息
>>> contacts = { '3951' : ['Bruce','IT','DBA'], '3091' : ['Jack','HR','HR'], '5122' : ['BlueTShirt','Sales','SecurityGuard'] }
7.1.2.訪問字典中的元素
>>> contacts['3951'][0]
'Bruce'
7.1.3.添加字典中的元素
- 沒有key,默認就是添加
>>> contacts['5927'] = ['Tang','BUG','土豪不需要職業']
>>> print contacts['5927'][2]
土豪不需要職業
7.1.4.修改字典中的元素
- 存在的key,就是修改
>>> contacts['5927'][0] = 'TangYan'
>>> contacts['5927'][0]
'TangYan'
7.2.字典的內置方法
7.2.1.清空字典
>>> contacts.clear()
7.2.2.潛復制字典
- 和list一樣潛復制這對二維或以上多維數據結構時,不是全完數據副本的拷貝
>>> copy_contacts = contacts.copy()
>>> contacts['3091'][0] = 'erha'
>>> contacts
{'3951': ['Bruce', 'IT', 'DBA'], '3091': ['erha', 'HR', 'HR'], '5122': ['BlueTShirt', 'Sales', 'SecurityGuard']}
>>> copy_contacts
{'3951': ['Bruce', 'IT', 'DBA'], '3091': ['erha', 'HR', 'HR'], '5122': ['BlueTShirt', 'Sales', 'SecurityGuard']}
- 深度復制
>>> deepcopy_contacts = copy.deepcopy(contacts)
>>> contacts
{'3951': ['Bruce', 'IT', 'DBA'], '3091': ['erha', 'HR', 'HR'], '5122': ['BlueTShirt', 'Sales', 'SecurityGuard']}
>>> contacts['3091'][0] = 'Jack'
7.2.3.初始化dict
- 和潛復制一樣都是有二級結構指針問題
>>> dict_module = dict.fromkeys(['BJ','SH','GZ'],['domain',{'module':'example.com'}])
>>> for k in dict_module: #遍歷字典
... print k,dict_module[k]
...
SH ['domain', {'module': 'example.com'}]
GZ ['domain', {'module': 'example.com'}]
BJ ['domain', {'module': 'example.com'}]
7.2.4.獲取dict的value
- 獲取字典中的value,找不到不拋出異常
>>> contacts.get('3951')
['Bruce', 'IT', 'DBA']
>>> contacts.get(3951)
7.2.5.判斷dict中的key是否存在
>>> contacts.has_key(3951)
False
>>> contacts.has_key('3951')
True
7.2.5.將dict轉換成list
- 一般用于遍歷字典使用,我們后面介紹語法及效率問題
>>> contacts.items()
[('3951', ['Bruce', 'IT', 'DBA']), ('3091', ['Jack', 'HR', 'HR']), ('5122', ['BlueTShirt', 'Sales', 'SecurityGuard'])]
7.2.6.返回字典的所有Key
>>> contacts.keys()
['3951', '3091', '5122']
- 判斷成員是否在字典的key中
>>> '3527' in contacts.keys()
True
7.2.7.返回字典的所有values
>>> contacts.values()
[['Bruce', 'IT', 'DBA'], ['Jack', 'HR', 'HR'], ['BlueTShirt', 'Sales', 'SecurityGuard']]
- 判斷成員是否在字典的value中
>>> test_dict = {'sansha':['erha','samo']}
>>> test_dict.values()
[['erha', 'samo']]
>>> test_dict.values()[0]
['erha', 'samo']
>>> 'erha' in test_dict.values()[0]
True
7.2.8.刪除dict元素
- 刪除dict元素,并返回刪除的value
>>> contacts.pop('3091')
['Jack', 'HR', 'HR']
7.2.9.隨機刪除dict元素
>>> contacts.popitem()
('3951', ['Bruce', 'IT', 'DBA'])
7.2.10.添加dict元素
- 添加dict元素,如果不寫value,則為空;如果存在及不創建
>>> contacts.setdefault('name_module')
>>> contacts.setdefault(3951,['Bruce','IT','DBA'])
['Bruce', 'IT', 'DBA']
7.2.11.合并dict
- 如果key沖突,則覆蓋原有value
>>> a ={ 1:'a',2:'2', 4:'5'}
>>> b = {1:2,2:3,3:4}
>>> a.update(b)
>>> a
{1: 2, 2: 3, 3: 4, 4: '5'}
7.3.字典的高級特性
7.3.1.多維字典的應用
- 聲明一個字典
site_catalog = {
"BJ":{
"noodle": ["pretty, good"],
"duck": ["Who eats"," ho regrets"],
"tiananmen": ["many people"],
},
"SH":{
"food":["i do not know","I heard that sweets mainly"]
},
"GZ":{
"vermicelli":["Looking at the scary", "eating is fucking sweet"]
}
}
- 字典的添加
>>> site_catalog['CD'] = {'gril':['White,','rich','beautiful']}
>>> #上下兩種方法都可以.
>>> site_catalog['CD']['boay'] = {}
>>> site_catalog['CD']['boay']['key'] = ['Tall', 'rich and handsome']
>>> site_catalog['BJ']['ditan'] = ['拜地']
- 字典的修改value
注意:dict不能修改字典的key,只能是刪除,在創建
>>> site_catalog['CD']['gril'][0] = 'Bai...'
- 字典的訪問
>>> site_catalog['CD']['gril'][0]
'White,'
>>> site_catalog['CD']['gril'].count('White')
0
- 三維字典的訪問
>>> for k in site_catalog:
... print "Title:%s" % k
... for v in site_catalog[k]:
... print "-> index:%s" % v
... for j in site_catalog[k][v]:
... if 'key' in site_catalog[k][v]:
... print '--> result:{}'.format(site_catalog[k][v][j])
... continue
... print '--> result:{}'.format(j)
...
Title:SH
-> index:food
--> result:i do not know
--> result:I heard that sweets mainly
Title:GZ
-> index:vermicelli
--> result:Looking at the scary
--> result:eating is fucking sweet
Title:BJ
-> index:tiananmen
--> result:many people
-> index:noodle
--> result:pretty, good
-> index:ditan
--> result:拜地
-> index:duck
--> result:Who eats
--> result: ho regrets
Title:CD
-> index:Gril
--> result:White,
--> result:rich
--> result:beautiful
-> index:boay
--> result:['Tall', 'rich and handsome']
-> index:gril
--> result:Bai...
--> result:rich
--> result:beautiful
7.3.2.遍歷字典比較
7.3.2.1.方法一
- itesm函數會將所有dict轉換成list,數據量大時dict轉換成list,效率超級低下
>>> contacts = {'3527': 'tangYan', '3951': {'Bruce': ['IT', 'DBA']}, '3091': {'Jack': ['HR', 'HR']}, '5122': {'BlueTShirt': ['Sales', 'SecurityGuard']}}
>>> for k, v in contacts.items():
... print k ,v
...
3527 tangYan
3951 {'Bruce': ['IT', 'DBA']}
3091 {'Jack': ['HR', 'HR']}
5122 {'BlueTShirt': ['Sales', 'SecurityGuard']}
7.3.2.2.方法二
- 最簡單的遍歷字典
>>> for i in contacts:
... print i,contacts[i]
...
3527 tangYan
3951 {'Bruce': ['IT', 'DBA']}
3091 {'Jack': ['HR', 'HR']}
5122 {'BlueTShirt': ['Sales', 'SecurityGuard']}
7.3.2.3.方法三
- 基于dict內置方法iteritems()迭代器(iterator)
items()是返回包含dict所有元素的list,但是由于這樣太浪費內存。性能也是極其的地下,所以就引入了iteritems(), iterkeys(), itervalues()這一組函數,用于返回一個 iterator 來節省內存;但是在 3.x 里items() 本身就返回這樣的 iterator,所以在 3.x 里items() 的行為和 2.x 的 iteritems() 行為一致,iteritems()這一組函數就廢除了。”
>>> for i in contacts.iteritems():
... print i
...
('3527', 'tangYan')
('3951', {'Bruce': ['IT', 'DBA']})
('3091', {'Jack': ['HR', 'HR']})
('5122', {'BlueTShirt': ['Sales', 'SecurityGuard']})
- iteritems()
>>> result_iterator = contacts.iteritems()
>>> result_iterator.next()
('3527', 'tangYan')
>>> result_iterator.next()
('3951', {'Bruce': ['IT', 'DBA']})
>>> result_iterator.next()
('3091', {'Jack': ['HR', 'HR']})
>>> result_iterator.next()
('5122', {'BlueTShirt': ['Sales', 'SecurityGuard']})
>>> result_iterator.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
- iterkeys()
>>> '3951' in contacts.iterkeys()
True
- itervalues()
>>> 'tangYan' in contacts.itervalues()
True
7.3.2.4.一致性
雖然Iterator被采納,評論卻指出,這種說法并不準確,在 3.x 里 items() 的行為和 2.x 的 iteritems() 不一樣,它實際上返回的是一個"full sequence-protocol object",這個對象能夠反映出 dict 的變化,后來在 Python 2.7 里面也加入了另外一個函數 viewitems() 和 3.x 的這種行為保持一致
創建一個測試dict
>>> d = {'size': 'large', 'quantity': 6}
>>> il = d.items()
>>> it = d.iteritems()
>>> vi = d.viewitems()
- 模擬字典被正常修改
d['newkey'] = 'newvalue'
- 驗證一下不同方式dict的結果
- 原生字典
>>> for i in d:
... print i, d[i]
...
newkey newvalue
quantity 6
size large
- items()字典
>>> for k, v in il:
... print k, v
...
quantity 6
size large
- iteritems()字典
>>> for k, v in it:
... print k, v
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
- viewitmes()字典
>>> for k, v in vi:
... print k, v
...
newkey newvalue
quantity 6
size large
總結:在 2.x 里面,最初是 items() 這個方法,但是由于太浪費內存,所以加入了 iteritems() 方法,用于返回一個 iterator,在 3.x 里面將 items() 的行為修改成返回一個 view object,讓它返回的對象同樣也可以反映出原 dictionary 的變化,同時在 2.7 里面又加入了 viewitems() 向下兼容這個特性。
所以在 3.x 里面不需要再去糾結于三者的不同之處,因為只保留了一個 items() 方法。
8.集合操作
在Python中set是基本數據類型的一種集合類型,是一個無序不重復元素集, 基本功能包括關系測試和消除重復元素. 集合對象還支持union(聯合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數學運算;它有可變集合(set())和不可變集合(frozenset)兩種。
8.1.集合基本操作
8.1.1.聲明集合
>>> a = set(range(1,6))
>>> b = set(range(5,10))
>>> a
set([1, 2, 3, 4, 5])
>>> b
set([8, 9, 5, 6, 7])
8.1.2.交集
>>> a & b
set([5])
或
>>> a.intersection(b)
set([5])
8.1.3.并集
>>> a | b
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
或
>>> a.union(b)
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
8.1.4.差集
>>> a - b
set([1, 2, 3, 4])
>>> b - a
set([8, 9, 6, 7])
或
>>> a.difference(b)
set([1, 2, 3, 4])
>>> b.difference(a)
set([8, 9, 6, 7])
8.1.5.對稱差集
- 取兩個集合中互相沒有的元素
>>> a ^ b
set([1, 2, 3, 4, 6, 7, 8, 9])
或
>>> a.symmetric_difference(b)
set([1, 2, 3, 4, 6, 7, 8, 9])
8.1.6.子集
- D是C的子集
>>> c = set([1,2,3,4,5,6,7])
>>> d = set([1,3,7])
>>> d <= c
True
或
>>> d.issubset(c)
True
8.1.7.父集
- C是D的父集
>>> c >= d
True
或
>>> c.issuperset(d)
True
8.1.8.成員測試
- 成員1在集合A的元素?
>>> 1 in a
True
- 成員1不在集合A的元素?
>>> 1 not in a
False
8.2.集合內置函數
8.2.1.添加一個元素
>>> a.add('haha')
8.2.2.清空集合A
>>> a.clear()
>>> print a
set([])
8.2.3.淺復制
- 老問題,呵呵不說了。
>>> a = set(range(1,6))
>>> e = a.copy()
8.2.4.隨機刪除元素
- 隨機刪除集合中的元素,并顯示被刪除的元素
>>> a.pop()
1
8.2.5.刪除元素
>>> a.remove(2)
8.2.6.合并集合
- 此時就能看出來集合的特性:去重功能
>>> a = set(range(1,6))
>>> b = set(range(3,8))
>>> a
set([1, 2, 3, 4, 5])
>>> b
set([3, 4, 5, 6, 7])
>>> a.update(b)
>>> a
set([1, 2, 3, 4, 5, 6, 7])
- 合并list測試
>>> a.update([5,6,7,8])
>>> a
set([1, 2, 3, 4, 5, 6, 7, 8])
9.作業
9.1.猜年齡作業
- 輸入用戶的信息
- 并且只有猜對年齡才能顯示
- 要求猜的機會只有10次
# !/bin/env python
# _*_ coding:utf-8 _*_
name = raw_input('Please imput your name:')
job = raw_input('job:')
salary = raw_input('salary:')
for i in range(10):
age = input('age:')
if age > 29:
print 'think smaller!'
elif age == 29:
print '\033[32;1mGOOD! 10 RMB!\033[0m'
break
else:
print 'think bigger!'
print 'You still got %s shots !' % (9 - i)
print '''
Personal information of %s:
Name: %s
Age : %d
Job : %s
salary : %s
''' % (name,name,age,job,salary)
9.2.用戶交互作業
- 用戶指定打印循環的次數
- 達到循環的次數是問用戶是否繼續
- 根據用戶選擇退出還是再次執行打印的循環次數
# !/bin/env python
# _*_ coding:utf-8 _*_
print_num = input('Which loop do you want it to be printed out?')
counter = 0
while True:
print 'Loop:', counter
if counter == print_num:
choice = raw_input('Do you want to continue the loop?(y/n)')
if choice == 'y' or choice == 'Y':
while print_num <= counter:
print_num = input('Which loop do you want it to be printed out?')
if print_num <= counter:
print '輸入值不得小于循環體的值'
elif choice == 'n' or choice == 'N':
print'exit loop....'
break
else:
print 'invalid input!'
continue
counter += 1
以上代碼能夠完成基本功能但是還有bug的地方
- 在執行choice 代碼塊時,用戶輸入,會有多余的loop打印
Do you want to continue the loop?(y/n)12
invalid input!
Loop: 5
- 代碼有重復代碼,這肯定是可以優化的兩個print_num用戶輸入
print_num = input('Which loop do you want it to be printed out?')
優化版
# !/bin/env python
# _*_ coding:utf-8 _*_
counter = 0
flag_1 = True
flag_2 = True
while True:
if flag_1 is True:
print 'Loop:', counter
else:
flag_1 = True
if flag_2 is True:
print_num = input('Which loop do you want it to be printed out?')
flag_2 = False
if counter == print_num:
choice = raw_input('Do you want to continue the loop?(y/n)')
if choice == 'y' or choice == 'Y':
while print_num <= counter:
print_num = input('Which loop do you want it to be printed out?')
if print_num <= counter:
print '輸入值不得小于循環體的值'
elif choice == 'n' or choice == 'N':
print'exit loop....'
break
else:
print 'invalid input!'
flag_1 = False
continue
counter += 1
9.3.購物車作業
- 輸入你的工資,進入商城選購商品
- 將商品放入購物車后,相應扣款
- 結束購物車時,清算商品及金額
- 并打印買的商品信息
#!/bin/env python
# _*_ coding:utf-8 _*_
products = [['Iphone',5800],['MacPro',12000],['NB Shoes',680],['MX4',64]]
salary = raw_input('Please input your salary: ')
shopping_list = []
if salary.isdigit():
salary = int(salary)
while True:
# print shoppint cart
for index,item in enumerate(products):
#print products.index(i),i
print index, item
# get user input
choice = raw_input('Please choose sth to buy')
# judge user input data type is number
if choice.isdigit():
choice = int(choice)
# judge goods count and seach goods index
if choice < len(products) and choice >= 0 :
pro_itmes = products[choice]
# judge Wage salary
if salary > pro_itmes[1] :
shopping_list.append(pro_itmes)
salary = salary - pro_itmes[1]
print('Added \033[31;1m%s\033[1m into shopping cart ,your current balance : %s' % (pro_itmes,salary))
else:
print('Sorry, your credit is running low : \033[41;1m%s\033[1m' % salary)
else:
print('input invalied!')
elif choice == 'q':
print("""------ shopping Cart------""")
for i in shopping_list:
print i
print('wage balance : \033[31;1m%s\033[1m ' % salary)
exit()
else:
print('There is no such commodity!')
else:
print('input error!')
9.4.地區查詢作業
- 打印省、市、縣、區、街道信息
- 可返回上一級
- 可以隨時退出程序,以下是所需dict:
menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'網易':{},
'google':{}
},
'中關村':{
'愛奇藝':{},
'汽車之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'鏈家':{},
'小販':{},
},
'天通苑':{},
'回龍觀':{},
},
'朝陽':{},
'東城':{},
},
'上海':{
'閔行':{
"人民廣場":{
'炸雞店':{}
}
},
'閘北':{
'火車戰':{
'攜程':{}
}
},
'浦東':{},
},
'山東':{},
}
exit_code = False
while not exit_code:
for i in menu:
print i
choire = raw_input('Please input city :')
if choire in menu:
while not exit_code:
for i2 in menu[choire]:
print i2
choire2 = raw_input('Please input area or cd .. (Y/N):')
if choire2 in menu[choire]:
if len(menu[choire][choire2]) <= 0 :
print "沒有信息!"
while not exit_code:
for i3 in menu[choire][choire2]:
print i3
choire3 = raw_input('Please input space or cd .. (Y/N):')
if choire3 in menu[choire][choire2]:
for i4 in menu[choire][choire2][choire3]:
print i4
choire4 = raw_input('cd .. (Y/N)')
if choire4 == 'Y':
pass
elif choire4 == 'q':
exit_code = True
if choire3 == 'Y':
break
elif choire3 == 'q':
exit_code = True
if choire2 == 'Y':
break
elif choire2 == 'q':
exit_code = True
- 附錄
- 運算符
- 條件語句
- 循環運算
- 字符串操作
- 列表操作
- 元組操作
- 字典操作
- 集合操作
- 作業