1. 程式人生 > >python基礎資料型別及內建容器詳解

python基礎資料型別及內建容器詳解

基礎資料型別

字串

如何在Python中使用字串:

1、使用單引號或者雙引號(‘、”)
用單引號括起來表示字串,例如:

str1='this is string'
print str1
str2="this is string"
print str2

2、使用三引號(”’)
利用三引號,表示多行的字串,可以在三引號中自由的使用單引號和雙引號,例如:

str='''this is string
this is pythod string
this is string'''
print str

布林型別

bool=False
print bool
bool=True
print
bool

整數

s=20
print s

浮點數

float=2.3
print float

物件引用

可以將變數名看成是對具體資料型別的指標,例如:

a=1
b='abcde'
c=3.0
del a
del b, c
print a #刪除a變數後,再呼叫a變數會報錯

數字型別de轉換

int(x [,base=m]) 將x轉換為一個m進位制的整數 (預設為10
example:int(‘10’,16)<<< a

float(x) 將x轉換到一個浮點數

complex(real [,imag]) 建立一個複數
example

:complex(1,5)<<< (1+5j)

str(x) 將物件x轉換為字串
repr(x) 將物件x轉換為表示式字串
example :hello = ‘hello, world\n’
str(hello)<<< hello, world
repr(hello)<<< “‘hello, world\n’”

eval(str) 用來計算在字串中的有效Python表示式,並返回一個物件
example:eval(“1+2+3+4”)<<< 10

tuple(s) 將序列s轉換為一個元組
list(s) 將序列s轉換為一個列表

chr(x) 將一個整數轉換為一個字元
ord(x) 將一個字元轉換為它的整數值
二者用於字元和ascii碼之間的轉換
example:ord(‘a’)<<< 97, chr(97)<<<‘a’

unichr(x) 將一個整數轉換為Unicode字元

hex(x) 將一個整數轉換為一個十六進位制字串
oct(x) 將一個整數轉換為一個八進位制字串

操作資料的數學函式

abs(x) 返回數字的絕對值,如abs(-10) 返回 10
pow(x, y) x**y 運算後的值。
cmp(x, y) 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
max(x1, x2,…) 返回給定引數的最大值,引數可以為序列。
min(x1, x2,…) 返回給定引數的最小值,引數可以為序列。
round(x [,n]) 返回浮點數x的四捨五入值,如給出n值,則代表舍入到小數點後的位數。
math.fabs(x) 返回數字的絕對值,如math.fabs(-10) 返回10.0
math.ceil(x) 返回數字的上入整數,如math.ceil(4.1) 返回 5
math.exp(x) 返回e的x次冪(ex),如math.exp(1) 返回2.718281828459045
math.floor(x) 返回數字的下舍整數,如math.floor(4.9)返回 4
math.log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0
math.log10(x) 返回以10為基數的x的對數,如math.log10(100)返回 2.0
math.modf(x) 返回x的整數部分與小數部分,兩部分的數值符號與x相同,整數部分以浮點型表示。
example:import math>>>math.modf(8)>>>(0.0,8.0)

math.sqrt(x) 返回數字x的平方根,數字可以為負數,返回型別為實數,如math.sqrt(4)返回 2+0j

內建容器

列表(list)

1、初始化列表

list=['woqu', 'nimei', 1997, 2000]
nums=[1, 3, 5, 7, 9, 11, 13]

2、訪問與擷取列表:

print "nums[0]:", nums[0] #列印第一個元素
>>>1
print "nums[2:5]:", nums[2:5] #從下標為2的元素切片到下標為5的元素,但不包含下標為5的元素
>>>[5, 7, 9]
print "nums[1:]:", nums[1:] #從下標為1切割到最後一個元素
>>>[3, 5, 7, 9, 11, 13]
print "nums[:-3]:", nums[:-3] #從最開始的元素一直切割到倒數第3個元素,但不包含倒數第三個元素
>>>[1, 3, 5, 7]
print "nums[:]:", nums[:] #返回所有元素
>>>[1, 3, 5, 7, 9, 11, 13]

3、更新列表

nums[0]="abc"
print nums[:]#返回所有元素
>>>['abc', 3, 5, 7, 9, 11, 13]

4、刪除列表元素

del nums[0]#無返回
print nums[:]#返回所有元素
>>>[3, 5, 7, 9, 11, 13]
nums.pop()#預設引數為-1
>>>13
print nums[:]#返回所有元素
>>>[3, 5, 7, 9, 11]
nums,pop(0)#刪除指定位置值
>>>3
print nums[:]#返回所有元素
>>>[5, 7, 9, 11]

5、列表指令碼操作符

print len([1, 2, 3])
>>>3
print [1, 2, 3] + [4, 5, 6]
>>>[1, 2, 3, 4, 5, 6]
print ['Hi!'] * 4
>>>['Hi!', 'Hi!', 'Hi!', 'Hi!']
3 in [1, 2, 3]
>>>True
for x in [1, 2, 3]: 
print x
>>>1 2 3

6、列表函式and方法

list.append(obj) 在列表末尾新增新的物件
list.count(obj) 統計某個元素在列表中出現的次數
list.extend(seq) 在列表末尾一次性追加另一個序列中的多個值(用新列表擴充套件原來的列表)
list.index(obj) 從列表中找出某個值第一個匹配項的索引位置,索引從0開始
list.insert(index, obj) 將物件插入列表
list.pop(index) 移除列表中的一個元素(預設最後一個元素),並且返回該索引對應的值
list.remove(obj) 移除列表中某個值的第一個匹配項
list.reverse() 反向列表中元素,倒轉
list.sort(cmp=None, key=None, reverse=False) 
    sort函式是序列的內部函式,原地排序,也就是使用後並不是返回一個有序的序列副本,而是把當前序列變得有序;
    sorted函式是python的內建函式,他接受一個序列,返回有序的副本,與sort的唯一區別就是會返回副本。

元組(tuple)

Python的元組與列表類似,不同之處在於元組的元素不能修改;元組使用小括號(),列表使用方括號[]。
1、初始化元組

list=('woqu', 'nimei', 1997, 2000)
nums=(1, 3, 5, 7, 9, 11, 13)

2、訪問與擷取元組:

print "nums[0]:", nums[0] #列印第一個元素
>>>1
print "nums[2:5]:", nums[2:5] #從下標為2的元素切片到下標為5的元素,但不包含下標為5的元素
>>>(5, 7, 9)
print "nums[1:]:", nums[1:] #從下標為1切割到最後一個元素
>>>(3, 5, 7, 9, 11, 13)
print "nums[:-3]:", nums[:-3] #從最開始的元素一直切割到倒數第3個元素,但不包含倒數第三個元素
>>>(1, 3, 5, 7)
print "nums[:]:", nums[:] #返回所有元素
>>>(1, 3, 5, 7, 9, 11, 13)

3、元組指令碼操作符

print len((1, 2, 3))
>>>3
print (1, 2, 3) + (4, 5, 6)
>>>(1, 2, 3, 4, 5, 6)
print ('Hi!') * 4
>>>('Hi!', 'Hi!', 'Hi!', 'Hi!')
3 in (1, 2, 3)
>>>True
for x in (1, 2, 3): 
print x
>>>1 2 3

6、元組函式and方法

tuple.count(obj) 統計某個元素在列表中出現的次數
tuple.index(obj) 從列表中找出某個值第一個匹配項的索引位置,索引從0開始
cmp(tuple1, tuple2) 比較兩個元組元素。
len(tuple) 計算元組元素個數。
max(tuple) 返回元組中元素最大值。
min(tuple) 返回元組中元素最小值。
tuple(list) 將列表轉換為元組。
sorted函式是python的內建函式,他接受一個序列,返回有序的副本,與sort的唯一區別就是會返回副本。

字典

字典(dictionary)是除列表之外python中最靈活的內建資料結構型別。列表是有序的物件結合,字典是無序的物件集合。兩者之間的區別在於:字典當中的元素是通過鍵來存取的,而不是通過偏移存取。
字典由鍵和對應的值組成。字典也被稱作關聯陣列或雜湊表。
1、初始化字典

dict={'nimei':123,1:123,'1':123,2:'234'}//method1
d = dict((('a',1),('b',2)))//method2:利用元組進行初始化

每個鍵與值必須用冒號隔開,每對用逗號分割,整體放在{}中。鍵必須獨一無二,但值則不必;值可以取任何資料型別,但必須是不可變的,如字串,數或元組。
2、訪問字典裡的值

print  dict['nimei']
>>>123
print  dict['1']
>>>123

3、修改字典

dict["nimei"]='woqu' #修改已有鍵的值
dict["woqu"]="111" #增加新的鍵/值對
print dict['nimei']
>>>'woqu'
print dict['woqu']
>>>'111'

4、清除字典資料

del dict['woqu']# 刪除鍵是'woqu'的條目
dict.clear()# 清空詞典所有條目
del dict  # 刪除詞典

5、字典內建函式&方法

cmp(dict1, dict2) 比較兩個字典元素。
len(dict) 計算字典元素個數,即鍵的總數。
str(dict) 輸出字典可列印的字串表示。
type(variable) 返回輸入的變數型別,如果變數是字典就返回字典型別。
dict.clear() 刪除字典內所有元素
dict.copy() 返回一個字典的淺複製
1. copy.copy 淺拷貝 只拷貝父物件,不會拷貝物件的內部的子物件。
2. copy.deepcopy 深拷貝 拷貝物件及其子物件
dict.fromkeys() 建立一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print "New Dictionary : %s" %  str(dict)
>>>New Dictionary : {'age': None, 'name': None, 'sex': None}
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" %  str(dict)
>>>New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

dict.items() 以列表返回可遍歷的(鍵, 值) 元組陣列
dict.keys() 以列表返回一個字典所有的鍵
dict.values() 以列表返回字典中的所有值
dict.has_key(key) 如果鍵在字典dict裡返回true,否則返回false
dict.get(key, default=None) 返回指定鍵的值,如果值不在字典中返回default值
dict.setdefault(key, default=None) 和get()類似, 但如果鍵不已經存在於字典中,將會新增鍵並將值設為default
dict.update(dict2) 把字典dict2的鍵/值對更新到dict裡

日期和時間

1、獲取當前時間

import time, datetime;
time.localtime(time.time())
>>>time.struct_time(tm_year=2016, tm_mon=3, tm_mday=17, tm_hour=18, tm_min=42, tm_sec=52, tm_wday=3, tm_yday=77, tm_isdst=0)

這裡寫圖片描述

2、獲取格式化的時間

日期轉換為字串

print time.strftime('%Y-%m-%d %H:%M:%S')
>>>'2016-03-17 18:49:01'
print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
>>>'2016-03-17 18:49:01'
print str(datetime.datetime.now())[:19]
>>>'2016-03-17 18:49:01'

字串轉換為日期

expire_time = "2013-05-21 09:50:35"
datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
>>>datetime.datetime(2013, 5, 21, 9, 50, 35)

獲取日期差

oneday = datetime.timedelta(days=1)
oneday 
>>>datetime.timedelta(1)
today = datetime.date.today()
today 
>>>datetime.date(2016, 3, 17)
yesterday = datetime.date.today() - oneday
yesterday 
>>>datetime.date(2016, 3, 16)
tomorrow = datetime.date.today() + oneday
tomorrow 
>>>datetime.date(2016, 3, 18)
today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S')
today_zero_time 
>>>'2016-03-17 00:00:00'
datetime.timedelta(milliseconds=1), #1毫秒
>>>datetime.timedelta(0, 0, 1000)
datetime.timedelta(seconds=1), #1秒
>>>datetime.timedelta(0, 1)
datetime.timedelta(minutes=1), #1分鐘
>>>datetime.timedelta(0, 60)
datetime.timedelta(hours=1), #1小時
>>>datetime.timedelta(0, 3600)
datetime.timedelta(days=1), #1天
>>>datetime.timedelta(1)
datetime.timedelta(weeks=1)
>>>datetime.timedelta(7)

字串日期格式化為秒數,返回浮點型別:

expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
d
>>> datetime.datetime(2013, 5, 21, 9, 50, 35)
time.mktime(d.timetuple())
>>>1369101035.0

日期格式化為秒數,返回浮點型別:

d = datetime.date.today()
time.mktime(d.timetuple())
>>>1458144000.0

秒數轉字串:

time_sec = time.time()
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec))
>>>'2016-02-17 11:14:02'