Python 數據基本類型



列表

序列是Python中最基本的數據結構。序列中的每個元素都分配一個數字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推。

Python有6個序列的內置類型,但最常見的是列表和元組。

序列都可以進行的操作包括索引,切片,加,乘,檢查成員。

此外,Python已經內置確定序列的長度以及確定最大和最小的元素的方法。

列表是最常用的Python數據類型,它可以作爲一個方括號內的逗號分隔值出現。

列表的數據項不需要具有相同的類型

如:[11,22,33]、['yefei', 'wusiqi']

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

訪問列表中的值

使用下標索引來訪問列表中的值,同樣你也可以使用方括號的形式截取字符,如下所示:

list1 = ['Google', 'Runoob', 1997, 2000];

list2 = [1, 2, 3, 4, 5, 6, 7 ];

print ("list1[0]: ", list1[0])

print ("list2[1:5]: ", list2[1:5])

以上實例輸出結果:

list1[0]:  Googlelist2[1:5]:  [2, 3, 4, 5]

更新列表

list = ['Google', 'Runoob', 1997, 2000]
print ("第三個元素爲 : ", list[2])
list[2] = 2001
print ("更新後的第三個元素爲 : ", list[2])

以上實例輸出結果:

第三個元素爲 :  1997更新後的第三個元素爲 :  2001

刪除列表

del()

list = ['Google', 'Runoob', 1997, 2000]
print (list)
del list[2]
print ("刪除第三個元素 : ", list)
del list      #刪除列表 整個元素

remove刪除指定方法

remove()
刪除制定的列表元素
a = [1,2,3]
a.remove(2)
print (a)
返回值
[1,3]


列表支持拼接操作:

list1 = [1,2,3]
list2 = [4,5,6]
list = list1 + list2
print (list)

輸出的值爲
[1,2,3,4,5,6]


嵌套列表

a = [1,2,3,4,5]
n = [6,7,8]
x = [a,n]
[[1,2,3,4,5],[6,7,8]]

Python列表函數&方法

len(list)列表元素個數
max(list)返回列表元素最大值
min(list)返回列表元素最小值
list(seq)將元祖轉換爲列表
list.append(obj)在列表末尾添加新的對象
list.count(obj)統計某個元素在列表中出現的次數
list.extend(seq)在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的)
list.index(obj)從列表中找出某個值第一個匹配項的索引位置
list.insert(index,obj)
將對象插入列表
list.pop(obj=list[-1])移除列表中的一個元素(默認最後一個元素,並且返回該值)

list.reverse()反向列表中的元素
list.sort()對原列表進行排序
list.clear()清空列表
list.copy()複製列表


字典

如:{'name': 'wupeiqi', 'age': 18} 、{'host': '2.2.2.2', 'port': 80]}

ps:循環時,默認循環key

dic = {'k1':'v1','k2':'v2'} 
dic = dict(k1='v1',k2='v2')

這兩個dic 是相等的


set集合

set是一個無序且不重複的元素集合

練習:尋找差異

# 數據庫中原有
old_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
}
  
# cmdb 新彙報的數據
new_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
}

1  原來沒有 -》 新加入

2, 原來有 -》 更新

3, 新無,原來有 -》 原來刪除

三個列表:

      要更新的數據

 要刪除

 要添加

old = set(old_dict.keys())
new = set(new_dict.keys())

#更新數據   交集
update_set = old.intersection(new)
print(update_set)

#刪除老的數據  添加新的數據   差集
delete_set = old.symmetric_difference(update_set)
print(delete_set)
add_set = new.symmetric_difference(update_set)
print(add_set)


#差集
#def difference() 循環old裏面的元素 如果update_set有的就刪除
#delete_set = old.difference(update_set)
#add_set = new.difference(update_set)

#差集
#delete_set = old.difference(new)

#add_set = new.difference(old)


計數器(counter)

Counter是對字典類型的補充,用於追蹤值的出現次數。

ps:具備字典的所有功能 + 自己的功能

c = Counter('abcdeabcdabcaba')
print c
輸出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
import  collections

#打印出元素的個數
obj = collections.Counter('adsdssdfsfsdsdfsdfsd')
print(obj)

#查看前4位元素
ret = obj.most_common(4)
print(ret)

#循環key值
for k in obj.elements(): 
    print(k)

#循環key值 和 鍵值
for k,v in obj.items():
    print(k,v)
 
#update方法    
obj = collections.Counter(['11','12','12','14'])
print(obj)
#添加
#obj.update(['eric','11','11'])
#print(obj)
#刪除
obj.subtract(['eric','11','11'])
print(obj)
返回值
Counter({'12': 2, '14': 1, '11': 1})
Counter({'12': 2, '14': 1, 'eric': -1, '11': -1})


有序字典(orderedDict )

orderdDict是對字典類型的補充,他記住了字典元素添加的順序

dic = collections.OrderedDict()
#dic = dict()   如果是基本的字典類型  輸出就是無序的
dic['k1'] = 'v1'
dic['k2'] = 'v2'
dic['k3'] = 'v3'
print(dic)

#默認值
dic['k4'] = None   這兩個相同   dic.setdefault('k4')

#popitem 刪除最後一個key
dic.popitem()
print(dic)

#move_to_end 把指定的key 最後輸出
dic.move_to_end('k1')
print(dic)

#pop 指定刪除 然後刪除的信息打印出來
ret = dic.pop('k2')
print(dic)
print(ret)

#update更新  添加元素到原先的字典當中 然後相同的key會自動更新
dic.update({'k1':'v111','k10':'v10'})
print(dic)

默認字典

defaultdict是對字典的類型的補充,他默認給字典的值設置了一個類型。

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
即: {'k1': 大於66 'k2': 小於66}
values = [11,22,33,44,55,66,77,88,99]
my_dict = collections.defaultdict(list)
for value in values:
    if value > 66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)


print(my_dict)

返回值
defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99]})


可命名元祖

根據nametuple可以創建一個包含tuple所有功能以及其他功能的類型。

練習

MytupleClass = collections.namedtuple('Mytuple',['x', 'y', 'z'])

obj = MytupleClass(11,22,33)

print(obj.x)
print(obj.y)
print(obj.z)

以後寫座標可以用到

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章