文章目录

  • dict
  • set
    • 4.用集合为列表去重
    • 5.集合的增 add,update
    • 6.集合的删 discard,remove,pop,clear
    • 7 集合运算
      • 7.1 子集(<或者issubset()方法)
      • 7.2并集(|或者union()方法)
      • 7.3 交集(&或者intersection())
      • 7.4 差集(-或者difference()方法)
      • 7.5 对称集(^或者symmetric_difference())
    • 8.集合的copy(浅复制)

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. """passdef 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. """passdef get(self, *args, **kwargs): # real signature unknown""" Return the value for key if key is in the dictionary, else default. """passdef items(self): # real signature unknown; restored from __doc__""" D.items() -> a set-like object providing a view on D's items """passdef keys(self): # real signature unknown; restored from __doc__""" D.keys() -> a set-like object providing a view on D's keys """passdef 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"""passdef 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."""passdef 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."""passdef 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] = vIn either case, this is followed by: for k in F:  D[k] = F[k]"""passdef 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是浅拷贝。

python基础 dict和set相关推荐

  1. Python基础 —— dict

    提供 copy 成员函数 内部有__len__,故可通过 len() 获得一个字典的长度: 0. D.get(k[,d]) vs D.setdefault() D.get(k[,d]) -> D ...

  2. Python基础知识(二)基本数据结构list列表和dict字典

    介绍 list和dict,顾名思义,就是列表和字典,这是python中非常基础的数据结构,也是非常重要且用途最广的数据结构 列表list就是一串糖葫芦 list是python的一种内置数据结构,想象成 ...

  3. Python基础数据结构之大循环(for list,set,dict,tuple)

    本章是Python基础数据结构的第六篇,由于之前没有接触过太多的Python版本的数据结构,所以在学习的过程中集百家之长和自己的见解,加以实践,学习Python. Python中用到tuple的方法, ...

  4. python基础-变量,变量类型,字符串str,元组tuple,列表list,字典dict操作详解(超详细)

    python基础--变量 (文章较长,若需要单独看某一个点,可点击目录直接跳转) 文章目录 python基础--变量 1. 变量 2. 变量类型 2.1数字类型 2.2 字符串 2.3 列表 2.4 ...

  5. python 等号报错_Python学习----Python基础

    Python基础 一.数据类型和变量 1.在Python中,等号=是赋值语句,可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量. 例如: a =520# a是整数prin ...

  6. python基础---元组、字典、函数、文件、异常

    文章目录 python基础---元组.字典.函数.文件.异常 Tuple(元组) 常用操作 dict(字典) 函数 文件 异常 python基础-元组.字典.函数.文件.异常 Tuple(元组) tu ...

  7. 刻意练习:Python基础 -- Task06. 字典与集合

    背景 我们准备利用17天时间,将 "Python基础的刻意练习" 分为如下任务: Task01:变量.运算符与数据类型(1day) Task02:条件与循环(1day) Task0 ...

  8. 刻意练习:Python基础 -- Task05. 函数与Lambda表达式

    背景 我们准备利用17天时间,将 "Python基础的刻意练习" 分为如下任务: Task01:变量.运算符与数据类型(1day) Task02:条件与循环(1day) Task0 ...

  9. 刻意练习:Python基础 -- Task01. 变量、运算符与数据类型

    背景 我们准备利用17天时间,将 Python 基础的刻意练习分为如下任务: Task01:变量.运算符与数据类型(1day) Task02:条件与循环(1day) Task03:列表与元组(2day ...

最新文章

  1. python脚本 通过rsa private key 生成 publickey
  2. 报错:ModuleNotFoundError: No module named ‘cv_bridge‘,以及在ROS是如何安装cv_bridge库包
  3. 初识 Vue(11)---(Vue 中的事件绑定)
  4. ubuntu16.04卸载firefox,然后再次安装firefox
  5. row_number() over()排序功能
  6. 12.04 ubuntu 安装微软雅黑的字体
  7. Bailian3721 和数【标记】
  8. Qt与Matlab混合编程细节总结
  9. Not a git repository (or any of the parent directories): .git
  10. jqueryUI日期控件和时间控件
  11. DAVE笔记--Micrium uc-Probo Oscilloscope调试
  12. UG NX 10 草图基础知识和概念
  13. android空间深度清理,安卓手机垃圾深度清理技巧
  14. 通过phpmyadmin修改帝国CMS的管理员密码
  15. 功放限幅保护_如何利用限幅器保护音箱
  16. mapStateToProps,mapDispatchToProps的使用详解
  17. httpclient调用京东万象数字营销频道新闻api实例
  18. vue中将base64的pdf文件流转换成pdf并预览(二)——base64转PDF工具的使用
  19. JS实现图片下载功能
  20. 猪肉涨价后,西游记剧情都变了

热门文章

  1. java中主线程首先执行_java经典面试题:子线程先运行30次主线程,主线程40次,如此循环50次?...
  2. erdas遥感图像几何校正_定量/高光谱遥感之—光谱分析技术
  3. 计算机技术qq交流群,专业计算机群QQ
  4. 宏基笔记本4740 Linux,宏基4740g拆机【教程详解】
  5. JavaScript时间日期函数
  6. (转)SQL Case when 的使用方法
  7. ES5 getter setter
  8. iOS 6 自动布局入门
  9. select * from dim.dim_area_no@to_dw
  10. 域名解析文件hosts文件是什么?如何修改hosts文件?