第7章 python映射和集合类型

1、映射类型:字典

1、如何创建字典和赋值

字典可用多种方式来创建:

  • 使用花括号内以逗号分隔 键: 值 对的方式: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}

  • 使用字典推导式{}{x: x ** 2 for x in range(10)}

  • 使用类型构造器

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
f = dict({'one': 1, 'three': 3}, two=2)
2、如何访问字典的值
a = {"1": "abc"}
for key in a.keys():
    print(key, a[key])
for key in a:
    print(key, a[key])
value = a["1"]

3、如何更新字典的值
a = {"1": "abc"}
a["1"] = "bcd"
4、如何删除字典的元素以及本身
del dict2['name'] # 删除键为“name”的条目
dict2.clear() # 删除 dict2 中所有的条目
del dict2 # 删除整个 dict2 字典
dict2.pop('name') # 删除并返回键为“name”的条目 

2、映射类型操作符
1、标准类型操作符 <>= !=
>>> dict4 = {'abc': 123}
>>> dict5 = {'abc': 456}
>>> dict6 = {'abc': 123, 98.6: 37}
>>> dict7 = {'xyz': 123}
>>> dict4 < dict5 
2、映射类型操作符

字典的键查找操作符([ ])

(键)成员关系操作( in ,not in)

3、映射的内建函数和工厂函数

1、标准类型函数

type() str()  cmp()

字典比较法顺序:

        1、比较字典的长度len

        2、比较字典的键key

        3、比较字典的值value

2、映射类型相关函数

dict()函数

>>> dict(zip(('x', 'y'), (1, 2)))
{'y': 2, 'x': 1}
>>> dict([['x', 1], ['y', 2]])
{'y': 2, 'x': 1}
>>> dict([('xy'[i-1], i) for i in range(1,3)])
{'y': 2, 'x': 1} 


>>> dict(x=1, y=2)
{'y': 2, 'x': 1}
>>> dict8 = dict(x=1, y=2)
>>> dict8
{'y': 2, 'x': 1}
>>> dict9 = dict(**dict8)
>>> dict9
{'y': 2, 'x': 1} 

len()函数

hash()函数

内建函数 hash()本身并不是为字典设计的方法,但它可以判断某个对象是否可以做一个字典的 键。将一个对象作为参数传递给 hash(), 会返回这个对象的哈希值。 只有这个对象是可哈希的, 才可作为字典的键 (函数的返回值是整数,不产生错误或异常),如果不能hash则产生异常

4、映射类型的内建方法

class dict(object):
    """
    dict() -> 空字典
    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) ->   dict(one=1, two=2)
    """

    def clear(self):  # real signature unknown; restored from __doc__
        """ 清空元素 """
        pass

    def copy(self):  # real signature unknown; restored from __doc__
        """浅拷贝 """
        pass

    @staticmethod  # known case
    def fromkeys(seq, val=None):  # real signature unknown
        """
        seq – 字典键值列表。
        value – 可选参数, 设置键序列(seq)对应的值,默认为 None。
        创建并返回一个新字典,其中 seq 的元素作为字典的键,val 作为所有键对应的
        初始值(若没给定,则默认为 None)
        """
        pass

    def get(self, key, default=None):  # real signature unknown
        """
        对于键 key 返回其对应的值,或者若 dict 中不含 key 则返回 default(注意,default
        的默认值为 None)
        """
        pass

    def items(self):  # real signature unknown; restored from __doc__
        """ 返回 dict 的(key, value)元组对的一个迭代版本⑥ """
        pass

    def keys(self):  # real signature unknown; restored from __doc__
        """ 返回 dict 所有键的一个迭代版本 """
        pass

    def pop(self, k, d=None):  # real signature unknown; restored from __doc__
        """
        类似于 get(),但删除并返回 dict[key](如果给定了 key);如果 key 不存在于 dict
        中且未给出 default,则抛出 KeyError 异常

        """
        pass

    def popitem(self, *args, **kwargs):  # real signature unknown
        """
        popitem的功能
        删除当前字典里末尾一组键值对并将其返回

        popitem的用法
        用法:
        dict.popitem()
        返回被删除的键值对,用元组包裹索引是key,1索引是value

        该函数的注意事项
        如果字典为空,会直接报错
        """
        pass

    def setdefault(self, *args, **kwargs):  # real signature unknown
        """
        类似于 get(),但如果 key 不存在于 dict 中,则设置 dict[key]=default
        """
        pass

    def update(self, E=None, **F):  # known special case of dict.update
        """
        update() 函数把字典dict2的 键 / 值 对更新到dict1里。
        """
        pass

    def values(self):  # real signature unknown; restored from __doc__
        """ 返回 dict 中值的一个迭代版本 """
        pass

    def __class_getitem__(self, *args, **kwargs):  # real signature unknown
        """ See PEP 585 """
        pass

    def __contains__(self, *args, **kwargs):  # real signature unknown
        """ True if the dictionary has the specified key, else False. """
        pass

    def __delitem__(self, *args, **kwargs):  # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs):  # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs):  # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y):  # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs):  # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):  # real signature unknown
        """ Return self>value. """
        pass

    def __init__(self, seq=None, **kwargs):  # known special case of dict.__init__
        """
        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)
        # (copied from class doc)
        """
        pass

    def __ior__(self, *args, **kwargs):  # real signature unknown
        """ Return self|=value. """
        pass

    def __iter__(self, *args, **kwargs):  # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs):  # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs):  # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):  # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod  # known case of __new__
    def __new__(*args, **kwargs):  # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs):  # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs):  # real signature unknown
        """ Return self|value. """
        pass

    def __repr__(self, *args, **kwargs):  # real signature unknown
        """ Return repr(self). """
        pass

    def __reversed__(self, *args, **kwargs):  # real signature unknown
        """ Return a reverse iterator over the dict keys. """
        pass

    def __ror__(self, *args, **kwargs):  # real signature unknown
        """ Return value|self. """
        pass

    def __setitem__(self, *args, **kwargs):  # real signature unknown
        """ Set self[key] to value. """
        pass

    def __sizeof__(self):  # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

5、字典的键

1、字典中的键是有类型限制的,只要是不可变类型就可以

2、不允许一个键对应多个值

3、键必须是可哈希的

6、集合类型

1、如何创建集合和赋值

集合被创建的唯一方法 - 用集合的工厂方法 set() 和 frozenset()

2、如何访问集合中的值

可以遍历查看集合成员或检查某项元素是否是一个集合中的成员

3、如何更新集合

只有可变集合能被修改。试图修改不可变集合会引发异常

>>> s.add('z')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's', 'z'])
>>> s.update('pypi')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y', 'z'])
>>> s.remove('z')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y'])
>>> s -= set('pypi') 
4、如何删除集合元素和本身

remove()、del()

7、集合类型操作符

1、标准类型操作符(所有的集合类型)

成员关系 (in, not in)

集合等价/不等价 、集合等价/不等价与集合的类型或集合成员的顺序无关

子集/超集:Sets 用 Python 的比较操作符检查某集合是否是其他集合的超集或子集。“小于”符号( , >= )用来判断超集。

2、集合类型操作符(所有的集合类型)
联合( | ) union()
>>> s | t
set(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's']) 
交集( & ) intersection()
>>> s & t
set(['h', 's', 'o', 'p'] 
差补/相对补集( – )difference()
对称差分( ^ )symmetric_difference()
a = set("abc")
b = set("bcd")
print(a | b, a & b, a - b, a ^ b)

{'b', 'c', 'd', 'a'} {'b', 'c'} {'a'} {'d', 'a'}

3、集合类型操作符(仅适用于可变集合)

(Union) Update ( |= )

保留/交集更新( &= )

差更新 ( –= )

对称差分更新( ^= )

8、内建函数

1、标准类型函数

len()str()type() cmp()

2、集合类型工厂函数

set() and frozenset()

9、操作符、函数\方法

1、可变集合
class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
    """

    def add(self, *args, **kwargs):  # real signature unknown
        """
        添加操作:将 obj 添加到 s 中
        """
        pass

    def clear(self, *args, **kwargs):  # real signature unknown
        """ 清空元素 """
        pass

    def copy(self, *args, **kwargs):  # real signature unknown
        """ 浅拷贝 """
        pass

    def difference(self, *args, **kwargs):  # real signature unknown
        """
        差集s – t 差操作:存在于 s 中且不存在于 t 中的元素。
        """
        pass

    def difference_update(self, *args, **kwargs):  # real signature unknown
        """ s -= t 差更新操作:s 仅仅包含 s 中不存在于 t 中的原始成员 """
        pass

    def discard(self, *args, **kwargs):  # real signature unknown
        """
        丢弃操作:remove()的更友好版本,如果 obj 存在于 s 中,则从 s 中移除 obj

        """
        pass

    def intersection(self, *args, **kwargs):  # real signature unknown
        """
        s & t 交操作:s 和 t 中的元素
        """
        pass

    def intersection_update(self, *args, **kwargs):  # real signature unknown
        """ s &= t 交更新操作:s 仅仅包含原始 s 与 t 的成员"""
        pass

    def isdisjoint(self, *args, **kwargs):  # real signature unknown
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs):  # real signature unknown
        """ Report whether another set contains this set. """
        pass

    def issuperset(self, *args, **kwargs):  # real signature unknown
        """ s >= t 超集测试(允许不适当的超集):t 所有的元素都是 s 的成员 """
        pass

    def pop(self, *args, **kwargs):  # real signature unknown
        """
        弹出操作:删除并返回 s 中的任意元素
        为空抛出异常
        """
        pass

    def remove(self, *args, **kwargs):  # real signature unknown
        """
        丢弃操作:如果 obj 存在于 s 中,则从 s 中移除 obj
        不存在抛出异常
        """
        pass

    def symmetric_difference(self, *args, **kwargs):  # real signature unknown
        """
        s ^ t 对称差操作:仅仅存在于 s 和 t 二者之一中的元素
        """
        pass

    def symmetric_difference_update(self, *args, **kwargs):  # real signature unknown
        """ s ^= t 对称差更新操作:s 只包含原始 s 和 t 二者之一中的成员 """
        pass

    def union(self, *args, **kwargs):  # real signature unknown
        """
        s | t 并操作:s 或 t 中的元素
        """
        pass

    def update(self, *args, **kwargs):  # real signature unknown
        """s |= t (联合)更新操作:把 t 中成员添加到 s 中. """
        pass

    def __and__(self, *args, **kwargs):  # real signature unknown
        """ Return self&value. """
        pass

    def __class_getitem__(self, *args, **kwargs):  # real signature unknown
        """ See PEP 585 """
        pass

    def __contains__(self, y):  # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass

    def __eq__(self, *args, **kwargs):  # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs):  # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __ge__(self, *args, **kwargs):  # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):  # real signature unknown
        """ Return self>value. """
        pass

    def __iand__(self, *args, **kwargs):  # real signature unknown
        """ Return self&=value. """
        pass

    def __init__(self, seq=()):  # known special case of set.__init__
        """
        set() -> new empty set object
        set(iterable) -> new set object

        Build an unordered collection of unique elements.
        # (copied from class doc)
        """
        pass

    def __ior__(self, *args, **kwargs):  # real signature unknown
        """ Return self|=value. """
        pass

    def __isub__(self, *args, **kwargs):  # real signature unknown
        """ Return self-=value. """
        pass

    def __iter__(self, *args, **kwargs):  # real signature unknown
        """ Implement iter(self). """
        pass

    def __ixor__(self, *args, **kwargs):  # real signature unknown
        """ Return self^=value. """
        pass

    def __len__(self, *args, **kwargs):  # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs):  # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):  # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod  # known case of __new__
    def __new__(*args, **kwargs):  # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs):  # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs):  # real signature unknown
        """ Return self|value. """
        pass

    def __rand__(self, *args, **kwargs):  # real signature unknown
        """ Return value&self. """
        pass

    def __reduce__(self, *args, **kwargs):  # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self, *args, **kwargs):  # real signature unknown
        """ Return repr(self). """
        pass

    def __ror__(self, *args, **kwargs):  # real signature unknown
        """ Return value|self. """
        pass

    def __rsub__(self, *args, **kwargs):  # real signature unknown
        """ Return value-self. """
        pass

    def __rxor__(self, *args, **kwargs):  # real signature unknown
        """ Return value^self. """
        pass

    def __sizeof__(self):  # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, *args, **kwargs):  # real signature unknown
        """ Return self-value. """
        pass

    def __xor__(self, *args, **kwargs):  # real signature unknown
        """ Return self^value. """
        pass

    __hash__ = None

2、不可变集合
class frozenset(object):
    """
    frozenset() -> empty frozenset object
    frozenset(iterable) -> frozenset object

    Build an immutable unordered collection of unique elements.
    """

    def copy(self, *args, **kwargs):  # real signature unknown
        """ Return a shallow copy of a set. """
        pass

    def difference(self, *args, **kwargs):  # real signature unknown
        """
        Return the difference of two or more sets as a new set.

        (i.e. all elements that are in this set but not the others.)
        """
        pass

    def intersection(self, *args, **kwargs):  # real signature unknown
        """
        Return the intersection of two sets as a new set.

        (i.e. all elements that are in both sets.)
        """
        pass

    def isdisjoint(self, *args, **kwargs):  # real signature unknown
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs):  # real signature unknown
        """ Report whether another set contains this set. """
        pass

    def issuperset(self, *args, **kwargs):  # real signature unknown
        """ Report whether this set contains another set. """
        pass

    def symmetric_difference(self, *args, **kwargs):  # real signature unknown
        """
        Return the symmetric difference of two sets as a new set.

        (i.e. all elements that are in exactly one of the sets.)
        """
        pass

    def union(self, *args, **kwargs):  # real signature unknown
        """
        Return the union of sets as a new set.

        (i.e. all elements that are in either set.)
        """
        pass

    def __and__(self, *args, **kwargs):  # real signature unknown
        """ Return self&value. """
        pass

    def __class_getitem__(self, *args, **kwargs):  # real signature unknown
        """ See PEP 585 """
        pass

    def __contains__(self, y):  # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass

    def __eq__(self, *args, **kwargs):  # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs):  # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __ge__(self, *args, **kwargs):  # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):  # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs):  # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(self, seq=()):  # known special case of frozenset.__init__
        """ Initialize self.  See help(type(self)) for accurate signature. """
        pass

    def __iter__(self, *args, **kwargs):  # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs):  # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs):  # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):  # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod  # known case of __new__
    def __new__(*args, **kwargs):  # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs):  # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs):  # real signature unknown
        """ Return self|value. """
        pass

    def __rand__(self, *args, **kwargs):  # real signature unknown
        """ Return value&self. """
        pass

    def __reduce__(self, *args, **kwargs):  # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self, *args, **kwargs):  # real signature unknown
        """ Return repr(self). """
        pass

    def __ror__(self, *args, **kwargs):  # real signature unknown
        """ Return value|self. """
        pass

    def __rsub__(self, *args, **kwargs):  # real signature unknown
        """ Return value-self. """
        pass

    def __rxor__(self, *args, **kwargs):  # real signature unknown
        """ Return value^self. """
        pass

    def __sizeof__(self):  # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, *args, **kwargs):  # real signature unknown
        """ Return self-value. """
        pass

    def __xor__(self, *args, **kwargs):  # real signature unknown
        """ Return self^value. """
        pass

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值