python基础 dict和set

dict

Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。

d = {‘Michael’: 95, ‘Bob’: 75, ‘Tracy’: 85}
下面使一些常用的方法:

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
    """ Create a new dictionary with keys from iterable and values set to value. """
    pass

def get(self, *args, **kwargs): # real signature unknown
    """ Return the value for key if key is in the dictionary, else default. """
    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, *args, **kwargs): # real signature unknown
    """
    Remove and return a (key, value) pair as a 2-tuple.
    
    Pairs are returned in LIFO (last-in, first-out) order.
    Raises KeyError if the dict is empty.
    """
    pass

def setdefault(self, *args, **kwargs): # real signature unknown
    """
    Insert key with a value of default if key is not in the dictionary.
    
    Return the value for key if key is in the dictionary, else default.
    """
    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
  1. dict的key必须是不可变对象

    这是因为dict根据key来计算value的存储位置,如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了。这个通过key计算位置的算法称为哈希算法(Hash)。

要保证hash的正确性,作为key的对象就不能变。在Python中,字符串、整数等都是不可变的,因此,可以放心地作为key。而list是可变的,就不能作为key。

set

set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

  1. 集合是一个无序可变不重复元素的序列(由于集合是无序的,所以不支持索引) , 集合的元素不能为可变类型(列表、字典、集合)
  2. 创建方式
    可以使用 { } 或 set( ) 创建集合,但是创建一个空集合时,只能使用set( )
  3. 集合的特点:
  • 无序性:集合中每个元素的地位是相同的,元素之间是无序的

  • 互异性:一个集合中,每个元素只能出现一次,任何元素之间都是不相同的

  • 确定性:给定一个集合,给定一个元素,该元素或属于该集合,或不属于该集合

4.用集合为列表去重

>>> list_1 = [1,4,6,8,1,4,6,8]
>>> list_1
[1, 4, 6, 8, 1, 4, 6, 8]
>>> set_1 = set(list_1)
>>> set_1
{8, 1, 4, 6}
>>> list_2=list(set_1)
>>> list_2
[8, 1, 4, 6]

5.集合的增 add,update

集合本省是可变的,所有可以增,删
增的方法有:

  • add :增加单个元素
  • update:增加多个元素,还可以使用其他,列表,元组,字符串或者其他集合作为参数

例子:

>>> k = {'x','y'}
>>> k.add('r')
>>> k.add('v','f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)
>>> k.update('v','f')
>>> k
{'f', 'x', 'v', 'r', 'y'}

从最后输出的值,我们发现,集合本身存储是没有顺序的。

6.集合的删 discard,remove,pop,clear

可以使用discard()和remove()方法删除集合中特定的元素
两者区别:如果集合中不存在指定元素,使用discard()保持不变,但是在这种情况下,remove()会引发KeyError.

>>> k
{'f', 'x', 'v', 'r', 'y'}
>>> k.discard('z')
>>> k.remove('z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'z'
>>> k.remove('x')
>>> k
{'f', 'v', 'r', 'y'}
>>> k.discard('y')
>>> k
{'f', 'v', 'r'}

此外还可以使用pop()方法返回并删除一个随机元素

>>> k
{'f', 'v', 'r'}
>>> k.pop()
'f'
>>> k
{'v', 'r'}
>>> k.clear()
>>> k
set()
  • 由于集合和无序的,会随机pop某个元素。

7 集合运算

运算符描述
s &= z把s更新为s和z的交集
s | =z把s更新为s和z的并集
s -= z把s更新为s和z的差集
s ^= z把s更新为s和z的对称差集
7.1 子集(<或者issubset()方法)
>>> A = set('hello')
>>> B = set('world')
>>> A
{'l', 'h', 'o', 'e'}
>>> B
{'o', 'l', 'w', 'r', 'd'}
>>> c= set('he')
>>> c < A
True
>>> c <B
False
>>> c.issubset(A)
True
7.2并集(|或者union()方法)
>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A|B
{'world', 'hello', 'beijing'}
>>> A.union(C)
{'world', 'hello', 'HELLO', 'Sh'}
7.3 交集(&或者intersection())
>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A&B
{'hello'}
>>> A.intersection(B)
{'hello'}
>>> 
7.4 差集(-或者difference()方法)

A-B的差集是所有属于A且 不属于B的元素构成的集合

>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A-B
{'world'}
>>> A.difference(B)
{'world'}
>>> A-C
{'world', 'hello'}
7.5 对称集(^或者symmetric_difference())

两个集合的对称集是只属于其中一个集合,而不属于另外一个集合的元素组成的集合

>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A ^B
{'beijing', 'world'}
>>> A.symmetric_difference(B)
{'beijing', 'world'}
>>> A.symmetric_difference(C)
{'world', 'hello', 'HELLO', 'Sh'}

可以理解为把两个集合进行了去重,然后组合成一个新的集合。

8.集合的copy(浅复制)

s = {'hello','world','beijing',frozenset('kkf')}
print(s)
s2=s.copy()
print(s2)

结果如下:
在这里插入图片描述

从运行结果来看,这里的copy是浅拷贝。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值