1. 程式人生 > >7基本數據類型4

7基本數據類型4

多個 個數 rem ping cas ini 求交集 mapping update

基本數據類型4

字典

集合

1:字典

字典是Python語言中唯一的映射類型。

定義:{key1:value1,key2:value2}

1、鍵與值用冒號":"分開;

2、項與項用逗號","分開;

特性:

1.key-value結構

2.key必須可hash、且必須為不可變數據類型、必須唯一

3.可存放任意多個值、可修改、可以不唯一

4.無序

字典的創建與常見操作

字典的創建:

person = {"name": "alex", ‘age‘: 20}

#

person = dict(name=‘seven‘, age=20)

#

person = dict({"name": "egon", ‘age‘: 20})

#

person = dict(([‘name‘,‘苑昊‘],[‘文周‘,18]))

{}.fromkeys(seq,100) #不指定100默認為None

#註意

>>> dic={}.fromkeys([‘k1‘,‘k2‘],[])

>>> dic

{‘k1‘: [], ‘k2‘: []}

>>> dic[‘k1‘].append(1)

>>> dic

{‘k1‘: [1], ‘k2‘: [1]}

字典的常見操作

鍵、值、鍵值對

    1、dic.keys() 返回一個包含字典所有KEY的列表;

    2、dic.values() 返回一個包含字典所有value的列表;

    3、dic.items() 返回一個包含所有(鍵,值)元祖的列表;

    4、dic.iteritems()、dic.iterkeys()、dic.itervalues() 與它們對應的非叠代方法一樣,不同的是它們返回一個叠代子,而不是一個列表;

新增

    1、dic[‘new_key‘] = ‘new_value‘;

    2、dic.setdefault(key, None) ,如果字典中不存在Key鍵,由 dic[key] = default 為它賦值;_

刪除

    1、dic.pop(key[,default]) 和get方法相似。如果字典中存在key,刪除並返回key對應的vuale;如果key不存在,且沒有給出default的值,則引發keyerror異常;

    2、dic.clear() 刪除字典中的所有項或元素;

修改

    1、dic[‘key‘] = ‘new_value‘,如果key在字典中存在,‘new_value‘將會替代原來的value值;

    2、dic.update(dic2) 將字典dic2的鍵值對添加到字典dic中

查看

    1、dic[‘key‘],返回字典中key對應的值,若key不存在字典中,則報錯;

    2、dict.get(key, default = None) 返回字典中key對應的值,若key不存在字典中,則返回default的值(default默認為None)

循環

    1、for k in dic.keys()

    2、for k,v in dic.items()

    3、for k in dic

長度

    1、len(dic)

字典的工廠函數:

class dict(object):

"""

dict() -> new empty dictionary

dict(mapping) -> new dictionary initialized from a mapping object‘s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {}

for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

"""

def clear(self): # real signature unknown; restored from __doc__

""" D.clear() -> None. Remove all items from D. """

pass

def copy(self): # real signature unknown; restored from __doc__

""" D.copy() -> a shallow copy of D """

pass

@staticmethod # known case

def fromkeys(*args, **kwargs): # real signature unknown

""" Returns a new dict with keys from iterable and values equal to value. """

pass

def get(self, k, d=None): # real signature unknown; restored from __doc__

""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """

pass

def items(self): # real signature unknown; restored from __doc__

""" D.items() -> a set-like object providing a view on D‘s items """

pass

def keys(self): # real signature unknown; restored from __doc__

""" D.keys() -> a set-like object providing a view on D‘s keys """

pass

def pop(self, k, d=None): # real signature unknown; restored from __doc__

"""

D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

"""

pass

def popitem(self): # real signature unknown; restored from __doc__

"""

D.popitem() -> (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

"""

pass

def setdefault(self, k, d=None): # real signature unknown; restored from __doc__

""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """

pass

def update(self, E=None, **F): # known special case of dict.update

"""

D.update([E, ]**F) -> None. Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]

If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v

In either case, this is followed by: for k in F: D[k] = F[k]

"""

pass

def values(self): # real signature unknown; restored from __doc__

""" D.values() -> an object providing a view on D‘s values """

pass

2:基本數據類型—集合

集合是一個數學概念:由一個或多個確定的元素所構成的整體叫做集合。

集合中的元素有三個特征:

1.確定性(元素必須可hash)

2.互異性(去重)

3.無序性(集合中的元素沒有先後之分),如集合{3,4,5}和{3,5,4}算作同一個集合。

註意:集合存在的意義就在於去重和關系運算

用集合解決問題

l= {‘張三‘,‘李四‘,‘老男孩‘} #集合定義

p = {‘張三‘,‘李四‘,‘alex‘}

l_p = l&p #集合求交集

print(l_p)

集合的定義

l= {1,2,3,1} #此處應說明集合"去重"的效果

#定義可變集合

>>> set_test=set(‘hello‘) #此處應說明集合的"無序性"

>>> set_test

{‘l‘, ‘o‘, ‘e‘, ‘h‘}

#改為不可變集合frozenset

>>> f_set_test=frozenset(set_test)

>>> f_set_test

frozenset({‘l‘, ‘e‘, ‘h‘, ‘o‘})

集合的關系運算:

交集 & intersection , 並集 | union , 差集 - difference , 對稱差集 ^ symmetric_difference ,

包含關系: in , not in 判斷某元素是否在集合內

== , != 判斷兩個集合是否相等

判斷兩個集合的關系:

set.isdisjoint(s):判斷兩個集合是不是不相交

set.issuperset(s):判斷集合是不是包含其他集合,等同於a>=b

set.issubset(s):判斷集合是不是被其他集合包含,等同於a<=b

並集:

>>> a = { 1 , 2 , 3 }

>>> b = { 1 , 2 , 4}

>>> print (a.union(b))

{1, 2, 3, 4}

>>> a|b

{1, 2, 3, 4}

交集:

>>> a&b

{1, 2}

>>> a.intersection(b)

{1, 2}

差集:

>>> a - b

{3}

>>> a.difference(b)

{3}

對稱差集:

>>> a^b

{3, 4}

>>> a.symmetric_difference(b)

{3, 4}

包含:in , not in

>>> for i in a :

... print (i in b, i)

...

True 1

True 2

False 3

>>> a == b

False

集合的關系:

>>> a

{1, 2, 3}

>>> d

{5, 6, 7}

>>> a.isdisjoint(b) # 是不是不相交

False # 不是的

>>> a.isdisjoint(d) # 是不是不相交

True # 是的

>>> a.issuperset(c)

True

>>> c.issubset(a)

True

7基本數據類型4