python基本數據類型
運算符
算數運算符
a,b = (10,20)
運算符 | 描述 | 實例 |
---|---|---|
+ | 加 - 兩個對象相加 | a + b 輸出結果 30 |
- | 減 - 得到負數或是一個數減去另一個數 | a - b 輸出結果 -10 |
* | 乘 - 兩個數相乘或是返回一個被重復若干次的字符串 | a * b 輸出結果 200 |
/ | 除 - x除以y | b / a 輸出結果 2 |
% | 取模 - 返回除法的余數 | b % a 輸出結果 0 |
** | 冪 - 返回x的y次冪 | a**b 為10的20次方, 輸出結果 100000000000000000000 |
// | 取整除 - 返回商的整數部分(向下取整) | >>> 9//2 4 >>> -9//2 -5 |
比較運算符
a,b = (10,20)
運算符 | 描述 | 實例 |
---|---|---|
== | 等於 - 比較對象是否相等 | (a == b) 返回 False。 |
!= | 不等於 - 比較兩個對象是否不相等 | (a != b) 返回 true. |
<> | 不等於 - 比較兩個對象是否不相等。python3 已廢棄。 | (a <> b) 返回 true。這個運算符類似 != 。 |
> | 大於 - 返回x是否大於y | (a > b) 返回 False。 |
< | 小於 - 返回x是否小於y。所有比較運算符返回1表示真,返回0表示假。這分別與特殊的變量True和False等價。 | (a < b) 返回 true。 |
>= | 大於等於 - 返回x是否大於等於y。 | (a >= b) 返回 False。 |
<= | 小於等於 - 返回x是否小於等於y。 | (a <= b) 返回 true。 |
賦值運算符
以下假設變量a為10,變量b為20:
運算符 | 描述 | 實例 |
---|---|---|
= | 簡單的賦值運算符 | c = a + b 將 a + b 的運算結果賦值為 c |
+= | 加法賦值運算符 | c += a 等效於 c = c + a |
-= | 減法賦值運算符 | c -= a 等效於 c = c - a |
*= | 乘法賦值運算符 | c *= a 等效於 c = c * a |
/= | 除法賦值運算符 | c /= a 等效於 c = c / a |
%= | 取模賦值運算符 | c %= a 等效於 c = c % a |
**= | 冪賦值運算符 | c **= a 等效於 c = c ** a |
//= | 取整除賦值運算符 | c //= a 等效於 c = c // a |
邏輯運算符
a,b = (10,20)
運算符 | 邏輯表達式 | 描述 | 實例 |
---|---|---|---|
and | x and y | 布爾"與" - 如果 x 為 False,x and y 返回 False,否則它返回 y 的計算值。 | (a and b) 返回 20。 |
or | x or y | 布爾"或" - 如果 x 是非 0,它返回 x 的值,否則它返回 y 的計算值。 | (a or b) 返回 10。 |
not | not x | 布爾"非" - 如果 x 為 True,返回 False 。如果 x 為 False,它返回 True。 | not(a and b) 返回 False |
示例

#and or not # 優先級,()> not > and > or print(2 > 1 and 1 < 4) print(2 > 1 and 1 < 4 or 2 < 3 and 9 > 6 or 2 < 4 and 3 < 2) # T or T or F #T or F print(3>4 or 4<3 and 1==1) # F print(1 < 2 and 3 < 4 or 1>2) # T print(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1) # T print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8) # F print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # F print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # F # ps int ----> bool 非零轉換成bool True 0 轉換成bool 是False print(bool(2)) print(bool(-2)) print(bool(0)) #bool --->int print(int(True)) # 1 print(int(False)) # 0
成員運算符
運算符 | 描述 | 實例 |
---|---|---|
in | 如果在指定的序列中找到值返回 True,否則返回 False。 | x 在 y 序列中 , 如果 x 在 y 序列中返回 True。 |
not in | 如果在指定的序列中沒有找到值返回 True,否則返回 False。 | x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。 |
身份運算符
身份運算符用於比較兩個對象的存儲單元
運算符 | 描述 | 實例 |
---|---|---|
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。 |
字符串
字符串常用功能:移除空白 分割 長度 索引 切片
字符串切片
a[start:end:step]
例子
s1 = 'hello world' print(s1[0:8]) #結果是 hello wo print(s1[0:8:2]) #結果是 hlow
字符串常用方法
len
len方法,計算字符串當的長度
s1 = "abc" len(s1) #結果是 3
find
find方法,在字符串中查找子串,如果可以找到,就返回子串的第一個字符的索引,否則就返回-1
s1 = 'hello world' s1.find('e') # 結果是1 s1.find('x') # 結果是 -1
index
count方法,在字符串中查找指定元素是否存在,存在就返回index
s1 = 'hello world' print(s1.index('h')) #結果是 0
count
count方法,查找指定的元素在列表中出現了多少次
s1 = 'hello world' print(s1.count('l')) #結果是 3
join
join方法,是一個非常重要的字符串方法,用於合並序列的元素
l1 = ['hello', 'world'] s1 = " ".join(l1) print(s1) #結果是 hello world
replace
replace方法,將指定的子串都替換為另一個字符串,並返回替換后的結果
s1 = 'hello world' print(s1.replace('h','HJ') ) #結果是 HJello world
strip
strip方法,將字符串開頭和末尾的空白(但不包括中間的空白)刪除,將返回刪除的結果
s1 = ' hello world ' print(s1.strip()) #結果是 'hello world' s2= '*190 190 190*' print(s2.strip('*')) #結果是 '190 190 190'
split
split方法,是一個非常重要的字符串方法,其作用余join相反,用於將字符串拆分為序列
s1 = 'wuhan zhangcheng beijin' print(s1.split() ) #結果是 ['wuhan', 'zhangcheng', 'beijin'] //全分割 print(s1.split(maxsplit=1)) #maxsplit:最多分隔幾次, #結果是 ['wuhan', 'zhangcheng beijin'] print(s1.split()[2] ) #結果是 'beijin' s2 = 'wuhan zhangcheng.zc' #以逗號為分隔符, print(s2.split('.',maxsplit=1)) #結果是 ['wuhan zhangcheng', 'zc']
center
center方法,通過在兩邊填充字符(默認為空格),讓字符串居中
print('zc'.center(10,'*')) #10是總長度,*是填充符 #結果是 '****zc****' print('zc'.center(3,'*') ) #結果是 '*zc' print('zc'.center(4,'*') ) #結果是 '*zc*'
just
使用ljust及rjust函數擴充字符串位數,不足用特殊字符填充
print('zc'.ljust(4,'*')) #結果是'zc**' print('zc'.rjust(4,'*')) #結果是'**zc'
upper
uppper方法,將字符串轉換為大寫輸出
s1 = 'zxxc' print(s1.upper()) #結果是 'ZXXC'
lower
lower方法,將字符串轉為小寫輸出
s1 = "ASD" print(s1.lower()) #結果是 'asd'
title
title方法,將字符串每個單詞首字母大寫
s1 = 'my name is zhangcheng' print(s1.title() ) #結果是 'My Name Is Zhangcheng'
capitalize
capitalize方法,只對一個首字母大寫
str = 'my name is zhangcheng' print(str.capitalize()) #結果是 'My name is zhangcheng'
startswitch
startswitch方法,以什么為開頭
print("hello".startswith("h")) #結果是 True print("hello".startswith("e")) #結果是 False
endswitch
endswitch方法,以什么為結尾
print("hello".endswith("o")) #結果是 True print("hello".endswith("h") ) #結果是 False
max
max方法,返回最大的字符
print(max('aAcC') ) #結果是 c
min方法,返回最小的字符串
print(min('aACc')) #結果是 A
判定字符串格式
# isupper() 有字母且均為大寫則為True print("AAAAAA".isupper()) #結果是True print("AAAAAb".isupper()) #結果是False # islower() 有字母且均為小寫則為True print("aaaa".islower()) #結果是True print("aaaaZ".islower()) #結果是False # istitle() 從左到右所有單詞首字母大寫 則為True print("I Have A Book!".istitle()) #結果是True print("I Have a Book!".istitle()) #結果是False
字符串格式化
Python的字符串格式化有兩種方式: 百分號方式、format方式 百分號的方式相對來說比較老,而format方式則是比較先進的方式,企圖替換古老的方式,目前兩者並存
百分號方式 %s %d %f
%s 字符串的格式化
%d 數字的格式化 %f 浮點數的格式化 >>print("name %s,%s" %('zx','xx')) 'name zx,xx' >>print("age%d" %(18)) 'age18' >>print("浮點數%7.2f" %(12.36)) # 7是長度,2是小數后幾位 '浮點數 12.36' >>print("浮點數%*.*f"%(20,4,12.23)) #20是長度,4是保留幾位小數 '浮點數 12.2300' >>print("浮點數%-*.*f"%(20,4,12.23)) #-號是左對齊 '浮點數12.2300 >>print("浮點數%0*.*f"%(20,4,12.23)) '浮點數000000000000012.2300'
format方式
>>print("name:{},age:{}".format("zc","18"))
'name:zc,age:18'
>>print("name:{0},age:{1}".format("zc","18")) 'name:zc,age:18' >>print("name:{1},age:{0}".format("zc","18")) 'name:18,age:zc' >>print("name:{1},{0},{1},age:{0}".format("zc","18")) 'name:18,zc,18,age:zc'
列表介紹
list的表達方式: [ ], 本質上是可以改變的序列
列表示例:
1.打印列表中的索引和元素:
for index,value in enumerate(b):
print("index:%d,value:%s" %(index,value)) a = [1,2,1,['zc','zx',1,2],4,1,1,1,1] for i in a: print(i)
2.打印某個值的index:
list_l = [1,1,2,3,4,3,2,1]
for index,value in enumerate(list_l): if value == 2: print(index)
>>x = list('perl')
>>print(x) >['p', 'e', 'r', 'l'] >>x[2:] = list('ra') >>print(x) ['p', 'e', 'r', 'a']
可將切片替換為長度與其不同的序列
>>x = list('perl')
>>print(x) ['p', 'e', 'r', 'l'] >>x[2:] = list('hello') >>print(x) ['p', 'e', 'h', 'e', 'l', 'l', 'o']
替換
在不替換原有元素的情況下插入新元素,“替換”了一個空切片,相當於插入了一個序列
x = ['1', '2', '3']
x[11100:1] = [6,7,8] print(x) #結果是 ['1', '2', '3', 6, 7, 8]
可采取相反的措施來刪除切片
x = ['1','2', '3', 6, 7, 8 ]
x[1:5] = [] print(x) #結果是 ['1', 8]
修改列表
列表賦值
x = [1, 1, 1]
x[1] = 2
print(x) #結果是 [1, 2, 1]
嵌套列表的使用
a = [1,2,3,['a','b','c']]
print(a[3]) #結果是:['a', 'b', 'c'] print(a[3][0]) #結果是 'a'
range 迅速產生一個列表
a = list(range(10))
print(a) #結果是 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ret = [i for i in range(100)]
print(ret) #結果是: [0,1,2,......,99] ret2 = [i*i for i in range(10)] print(ret2) #結果是 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ret3 = [chr(i) for i in range(ord('a'),ord('a')+26)] print(ret3) #結果是 ['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']
刪除元素
a = [1,2,1,4,1,1,1,1]
for i in range(a.count(1)): a.remove(1) print(a) #結果是 [2,4]
列表常用方法
append
方法append用於將一個對象附加到列表末尾。
lst = [1, 2, 3]
lst.append(4) print(lst) #結果是 [1, 2, 3, 4] a = ['1', '2', '3'] b = ['4', '5', '6'] a.append(b) print(a) #結果是 ['1', '2', '3', ['4', '5', '6']]
insert
方法insert用於將一個對象插入列表。
numbers = [1, 2, 3, 5, 6, 7]
numbers.insert(3, 'four') print(numbers) #結果是 [1, 2, 3, 'four', 5, 6, 7]
pop
不指定索引,就默認刪除最后一個元素,指定索引的話,就刪除與索引對應的元素,刪除完成之后,並返回這一元素
x = [1, 2, 3]
print(x.pop()) #結果是 3 x = [1,2] print(x.pop(0)) #結果是 1 print(x) #結果是 [2]
remove
方法remove用於刪除第一個為指定值的元素。
x = ['to', 'be', 'or', 'not', 'to', 'be']
x.remove('be') print(x) #結果是 ['to', 'or', 'not', 'to', 'be']
方法count計算指定的元素在列表中出現了多少次
x = ['to', 'be', 'or', 'not', 'to', 'be']
print(x.count('to')) #結果是 2
clear
方法clear就地清空列表的內容
lst = [1, 2, 3]
lst.clear()
print(lst) #結果是 []
del
刪除元素和變量
x = [1,2,3,4,5,6,7]
del x[0] print(x) #結果是 [2, 3, 4, 5, 6, 7] del x print(x) #結果報錯,列表不存在,NameError: name 'x' is not defined
sort
方法sort用於對列表就地排序。就地排序意味着對原來的列表進行修改,使其元素按順序排列,而不是返回排序后的列表的副本。
x = [4, 6, 2, 1, 7, 9]
x.sort()
print(x) #結果是 [1, 2, 4, 6, 7, 9]
sorted
方法sorted返回一個排好序的列表,源列表不變
x = [1,3,5,23,3,4]
sorted(x)
#結果是 [1, 3, 3, 4, 5, 23]
print(x) #結果是 [1, 3, 5, 23, 3, 4],源列表不變
max和min
輸出列表中最大值和最小值
x = [1, 3, 5, 23, 3, 4]
print(max(x)) #結果是23 print(min(x)) #結果是1
copy
copy方法 ,copy 復制列表。前面說過,常規復制只是將另一個名稱關聯到列表。
淺拷貝
a = [1, 2, 3]
b = a b[1] = 4 print(a) #結果是 [1, 4, 3] print(id(a)) #結果是 10044840 print(id(b)) #結果是 10044840
import copy
#結果是
a = [1, 2, 3] b = copy.deepcopy(a)#或者使用b = a.copy()
# 要讓a和b指向不同的列表,就必須將b關聯到a的副本
b[1] = 4 print(a) #結果是 [1, 4, 3] print(id(a)) #結果是 10044840 print(id(b)) #結果是 10044840
extend
方法extend讓你能夠同時將多個值附加到列表末尾,為此可將這些值組成的序列作為參數提供給方法extend。換而言之,你可使用一個列表來擴展另一個列表。
a = [1, 2, 3]
b = [4, 5, 6] a.extend(b) print(a) #結果是 [1, 2, 3, 4, 5, 6]
index
方法index在列表中查找指定值第一次出現的索引
knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
print(knights.index('who')) #結果是 4
方法reverse按相反的順序排列列表中的元素(我想你對此應該不會感到驚訝)
x = [1, 2, 3]
x.reverse()
print(x) #結果是 [3, 2, 1] # 注意到reverse修改列表,但不返回任何值(與remove和sort等方法一樣)
list
list方法,將其他元素轉換為列表
s = "china"
s1 = list(s) print(s1) #結果是 ['c', 'h', 'i', 'n', 'a']
字典
字典:是一個無序的容器,由鍵值對組成,不同鍵值對用逗號隔開,鍵和值用冒號隔開,鍵要唯一,且是可hash對象 不可變對象,int str tuple;值是list set tuple dict 可變對象
如:dict = {"name":'eric', "age":18, "fav":[ "pingpong",'footbool'] }
字典賦值 dict_a["xxx"]=value xx存在則覆蓋,不存在則追加。
示例:
dict = {"name":'eric', "age":18, "fav":[ "pingpong",'footbool'] }
dict["name"] = "zhangcheng" dict["salary"] = 10000000 print(dict) #結果是 {'name': 'zhangcheng', 'age': 18, 'fav': ['pingpong', 'footbool'], 'salary': 10000000}
get
a = {1:'zc',2:'zx'}
print(a.get(1)) #結果是 'zc'
獲取所有的鍵
a = {1:'zc',2:'zx'}
print(a.keys()) #結果是 dict_keys([1, 2])
values
獲取所有的值
a = {1:'zc',2:'zx'}
print(a.values()) #結果是 dict_values(['zc', 'zx'])
將字典的key轉換成列表
a = {1: 'zc', 2: 'zx', 'zhangcheng': 123}
print(list(a)) #結果是 [1, 2, 'zhangcheng']
pop
將某個鍵值對給刪除,通過鍵值來獲取:
a = {1: 'zc', 2: 'zx', 'zhangcheng': 123}
print(a.pop(1)) #結果是 'zc' print(a) #結果是 {2: 'zx', 'zhangcheng': 123}
popitem
隨機移除一個鍵值對,並以元組的形式返回
a = {2: 'zx', 'zhangcheng': 123}
print(a.popitem()) #結果是 ('zhangcheng', 123) print(a) #結果是 {2: 'zx'}
clear
清空一個字典
b = {'a': 1, 'b': 2, 'c': 3}
b.clear()
print(b) #結果是 {}
del
刪除一個字典
b = {"age":"18"}
del b print(b) #結果是 # Traceback (most recent call last): # File "<pyshell#77>", line 1, in <module> # b # NameError: name 'b' is not defined
copy
a = {'a': 1, 'b': 2, 'c': 3}
b = a.copy() print(b) #結果是 {'a': 1, 'b': 2, 'c': 3}
c = dict.fromkeys([1,2,3],'OK')
print(c) #結果是 {1: 'OK', 2: 'OK', 3: 'OK'}
dict
print(dict([('a',1),('b',2)]))
#結果是 {'a': 1, 'b': 2}
items
同時獲取一個鍵值對的鍵和值
a = {1:3,2:4,3:5}
print(a.items()) print(list(a.items())) #結果是 dict_items([(1, 3), (2, 4), (3, 5)]) #結果是 [(1, 3), (2, 4), (3, 5)]
zip
快速構建字典
print(zip([1,2],[2,3,4]))
#結果是 <zip object at 0x03592260>
print(list(zip([1,2],[2,3,4]))) #結果是 [(1, 2), (2, 3)] Keys = [1,2,3,4,5,6] Values = [3,4,5,6,7,8] print(dict(zip(Keys,Values))) #結果是 {1: 3, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8}
集合
set 定義空集合:a=set()
{1,2,3,4}
集合中元素必須為不可變對象。 可hash對象集合元素是不重復的,唯一的。
集合常用方法
add
a = {1, 2, 36, 5564, 14}
a.add(40) print(a) # {1, 2, 36, 40, 14, 5564}
update
把原來集合中沒有的元素重其他集合導入、更新
a = {1,2,3}
a.update({4,5,6}) print(a) #{1, 2, 3, 4, 5, 6}
remove
刪除集合中元素,如果元素不存在則報錯
a = {1,2,3,4, 5, 6}
a.remove(6) print(a) #{1, 2, 3, 4, 5} a = {1,2,3,4, 5, 6} a.remove(0) print(a) #Traceback (most recent call last): # File "F:/study/python/code/demo/demo_list.py", line 10, in <module> # a.remove(0) # KeyError: 0
discard
a = {1,2,3,4, 5, 6}
a.discard(6) print(a) #{1, 2, 3, 4, 5} a.discard(0) print(a) # {1, 2, 3, 4, 5}
set
set的簡易用法:刪除重復的元素
lst = [1,1,2,3,2,23,45,6,6]
new_lst = list(set(lst)) print(new_lst) # [1, 2, 3, 6, 45, 23]
集合求交集
a = {1,2,3,4}
b = {4,5,6,7} print(a & b) # {4} print(a.intersection(b)) # {4}
集合求並集
a = {1,2,3,4}
b = {4,5,6,7} print(a | b) # {1, 2, 3, 4, 5, 6, 7} print(a.union(b)) # {1, 2, 3, 4, 5, 6, 7}
集合求差集
a = {1,2,3,4,5,6,7}
b = {4,5,6,7} print(a - b) # {1, 2, 3} print(a.difference(b)) # {1, 2, 3}
元組
元祖 只讀列表,可循環查詢,可切片。
>>> tu = (1,2,3,[1,2,3])
>>> tu[0] = 100 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> tu[-1][0] = 100 >>> tu (1, 2, 3, [100, 2, 3])
>>> t = ()
>>t () >>> print(type(t)) <class 'tuple'> >>> t = tuple() >>> t () >>> print(type(t)) <class 'tuple'> >>> t = (1) 此時t是數字類型 >>> print(type(t)) <class 'int'> >>> t = (1,) >>> print(type(t)) <class 'tuple'>
查看元素為1的index
>>a = (1,'zc')
>>a.index(1) 0
count
查看元素出現的次數
>>a = (1,'zc')
>>a.count(1) 1
元組和列表之間的相互轉換,使用tuple和list方法:
>>a = [1,2,3]
>>b = tuple(a) >>b (1, 2, 3) >>c = list(b) >>c [1, 2, 3]
推導式
ret = [i for i in range(1,11) if i%2 == 0 ]
print(ret) #[2, 4, 6, 8, 10]
例二:10以內可以被2整除的數的平方
ret = [i*i for i in range(1,11) if i%2 == 0]
print(ret) # [4, 16, 36, 64, 100]
例三:找到嵌套列表中名字含有兩個‘e’的所有名字
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']] ret = [ name for lst in names for name in lst if name.count('e') >= 2] print(ret) # ['Jefferson', 'Wesley', 'Steven', 'Jennifer']
例一:將一個字典的key和value對調
mcase = {'a': 10, 'b': 34}
mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency) # {10:'a' , 34:'b'}
例二:合並大小寫對應的value值,將k統一成小寫
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase} print(mcase_frequency) # {'a':17,'b':34,'z':3}
squared = {x*x for x in [1, -1, 2]}
print(squared) # {1, 4}
str_a = "hello"
ret = 1000 if len(str_a) >= 3 else 1
print(ret) # 1000