
python基本數(shù)據(jù)類型總結(jié)
整數(shù)int與浮點(diǎn)數(shù)float
整數(shù)運(yùn)算永遠(yuǎn)是精確的,浮點(diǎn)數(shù)的運(yùn)算可能會(huì)有四舍五入。
2/2結(jié)果為1.0
// 表示整除 2//2結(jié)果為1
3//2也是1 并不是四舍五入,而是只保留整數(shù)部分
1.23x10^9和 12.3x10^8相等
1.23x10^9就是1.23e9,或者12.3e8,0.000012可以寫成1.2e-5
進(jìn)制
python中默認(rèn)為10進(jìn)制。
2進(jìn)制用0b表示,例如0b10即為2。
8進(jìn)制用0o表示,例如0o10即為8。
16進(jìn)制用0x表示,例如0x10即為16。(8,9,a,b,c,d,e,f,0x10)
bin() #轉(zhuǎn)化為2進(jìn)制
oct() #轉(zhuǎn)化為8進(jìn)制
int() #轉(zhuǎn)化為10進(jìn)制
hex() #轉(zhuǎn)化為16進(jìn)制
布爾值bool
bool()
bool(0)
bool('')
bool([])
bool(set())
bool({})
bool(None)
只有bool(0)和bool()括號(hào)中為空才表示Fasle。bool(’0‘)等表示True
序列
字符串 str 可用單引號(hào),雙引號(hào)或者三引號(hào)表示例如'str' 或"str "或者'''str'''
其中三引號(hào)常用方式如下
'''
line1
line2
.
.
'''
在字符串前面加一個(gè)R/r 表示原始字符串
print(r'\t\r') # \t\r
一些轉(zhuǎn)義字符(特殊的字符)
\n #換行 無法“看見”的字符
\' #單引號(hào) 與語言本身有沖突的字符
\t #橫向制表符
\r #回車
\n #換行
\\ #表示\
元組 tuple ( )與列表list [ ]
元組與列表在python中的唯一區(qū)別就是:元組是不可變的,列表是可變的。(元組和字符串是不可變的)
a = 'hello'
a=a+'world'
print(a) #'helloworld' a變成了一個(gè)新的字符串,而不是改變了字符串
#列表可變
b=[1,2,3]
b.append(4)
print(b) #[1,2,3,4]
#改變的是列表不是元組
c = (1,2,3,[4,5,['a','b','c']])
c[3][2][1] = 'd'
c[3][0]='6'
c[3][1]=7
#c[2]=8 #會(huì)報(bào)錯(cuò),因?yàn)樵M不能被改變'tuple' object does not support item assignment
print(c) #(1, 2, 3, ['6', 7, ['a', 'd', 'c']]) 改變的是列表 而不是 元組
在你有一些不確定長度的相同類型隊(duì)列的時(shí)候使用列表;在你提前知道元素?cái)?shù)量的情況下使用元組,因?yàn)樵氐奈恢煤苤匾?/p>
#元組
(1,2,3)
((1,2,3),(4,'hello',True))
(1,2,[3,4],{5,6},{(1,2,3):10,'hello':11,100:'hello'})
() #空元組
(1,) #一個(gè)元素的元組
#列表
[1,2,3]
[[1,2,3],[4,'hello',True],(1,2,3),{7,8}{(1,2,3):10,'hello':11,100:'hello'}]
A=1,2,3,4 #A為元組,即A=(1,2,3,4)
序列可以進(jìn)行加法,與整數(shù)相乘,切片操作
#與整數(shù)相乘
'python'*3 # 'pythonpythonpython'
((1,2,3),(4,'hello',True))*2 # ((1, 2, 3), (4, 'hello', True), (1, 2, 3), (4, 'hello', True))
[[1,2,3],[4,'hello',True],(1,2,3)]*2 #[[1, 2, 3], [4, 'hello', True], (1, 2, 3), [1, 2, 3], [4, 'hello', True], (1, 2, 3)]
#同類型相加
'hello'+'world' # 'helloword'
((1,2,3),(4,'hello',True))+(7,8,9) #((1, 2, 3), (4, 'hello', True), 7, 8, 9)
[[1,2,3],[4,'hello',True],(1,2,3)]+[4,5,6] #[[1, 2, 3], [4, 'hello', True], (1, 2, 3), 4, 5, 6]
#切片
'hello world'[0] # 'h' 從0開始
'hello world'[-1] # 'd' 從末尾往前數(shù)1
'hello world'[1:4] # 'ell' 從1開始,4前一位結(jié)束
'hello world'[0:-2] # 'hello wor' 從開頭到末尾減去2位
'hello world'[:-5] # 'hello ' 從開頭到末尾減去5個(gè)字符
'hello world'[1:-2] #'ello wor' 從1到末尾減去2位
'hello world'[6:100] # 'world' 超過,從第6位取到末尾
'hello world'[6:] # 'world' 從第6位取得末尾
'hello world'[-1:2] #'’‘ 空字符串,不能這樣做
集合set {}和字典dict {}
集合和字典的特點(diǎn)是 無序,不重復(fù)
set()表示空集合
{} 表示空字典
- #可以用來求兩個(gè)集合的差集
+ #可以用來求兩個(gè)集合的交集
| #可以用來求兩個(gè)集合的合集
字典是通過key訪問value{key1:value1,key2:value2}
key不能重復(fù),類型為int,str,tuple
value可以為任意數(shù)據(jù)
序列和集合的其他運(yùn)算
len() #求元素總和
max() #求最大的元素
min() #求最小的元素 比較的是 ord
in ,not in #成員關(guān)系運(yùn)算符
3 in [1,2,3] #True
3 in [1,2,[3,4]] #False
'3' in 's3' #True