#coding=utf-8
import random
#字典 & 集合
##字典
dictionary_1 = {'key1':'1','key2':'2'}
dictionary_2 = dict(key1 = '1',key2 = '2') #dict()创建字典函数
key = ['1','2']
values = ['1','2']
dictionary_3 = dict(zip(key,values)) #zip()先打包成一个元组,然后返回这些元组组成的列表,使用tuple()转换zip对象为元组,list()为列表,dict()为字典
name_list = ('key1','key2') #键
dictionary_4 = dict.fromkeys(name_list) #fromkeys()方法创建值为空的字典
name_tuple = ('1','2') #整个元组作为一个键
values_list = ['hh','xx'] #整个列表作为一个值
dictionary_5 = {name_tuple:values_list} #通过已存在的元组和列表创建字典
print(dictionary_5['1'] if '1' in dictionary_5 else "字典中无此选项")
print("字典值为:",dictionary_5.get(('1','2'),'字典无此选项')) #get方法获取指定键值
dictionary_5['3'] = 'cc' #添加字典元素
dictionary_5['1','2'] = '修改后的值' #修改字典元素
for item in dictionary_5.items(): #遍历字典print(item)
for key in dictionary_5.keys(): #遍历所有键print(key)
for value in dictionary_5.values(): #遍历所有值print(value)
dictionary_5.pop('3') #删除字典元素
dictionary_5.clear() #清空字典
#range()函数创建整数列表,range(start,stop,step)默认从0开始,计数到stop结束但不包括stop,step步长默认为1
randomdict = {i:random.randint(10,30) for i in range(5)} #字典推到式
print("生成的字典为:",randomdict)##集合(用于去重,输入重复的元素只保留一个;集合是无序的,每次输出的元素排序会不同)
set_1 = {'1','2','3'} #创建集合
set_2 = set(('ss','ss2')) #可以set元组、列表、range对象、字符串
set_3 = set(['1','2'])
set_4 = set(range(2,9,2))
set_5 = set("I like python python")
set_6 = set() #创建空集合,{}表示的是空字典,所以创建空集合用set()
print(set_1,set_2,set_3,set_4,set_5)
set_5.add('ios')
set_5.add("Android")
set_5.remove('Android')
set_5.pop() #随机删除一个元素
set_5.clear() #清空集合
print(set_5)
print("集合的交集运算:",set_1 & set_3)
print("集合的并集运算:",set_1 | set_3)
print("集合的差集运算:",set_1 - set_3)
详细解决方案
python的字典 & 集合
热度:43 发布时间:2024-01-26 07:15:14.0
相关解决方案
- ubuntu9.04上安装mic2 出错 (python setup.py build)
- ubuntu9.04下安装mic2 出错 (python setup.py build),该如何解决
- python sybase装配
- python(django框架) + mysql 的编码有关问题,求解
- SAE python web.py bootstrap 开发记要
- 数目字代码把大数据数字口语化(python+js) 数字代码
- python JSON string 的中文有关问题
- python――施用yaml数据格式,PK -> XML,JSON
- Learn Python The Hard Way学习(52) - 开始您的web游戏
- Python 相关有关问题
- 菜鸟,先学JAVA,还是Ruby,python
- 【大哥大姐】python 操作MS SQL Server 2005 效率
- python serial模块运用
- python scp自动登录解决方法
- 【Python】按行读取文件、IOError: [Errno 22] invalid mode ('a+') or filename,处置文件的换行符
- Python 3.x中使用print函数出现语法异常(SyntaxError: invalid syntax)的原因
- 【Error】Python安装gevent时出错:“致命异常: Python.h:没有那个文件或目录”
- [Python]attributeError:'module' object has no attribute 'dump'
- Python 出错:IndentationError: unexpected indent
- Python“TypeError: 'NoneType' object is not iterable"的缘故
- python in操作挑动 TypeError
- 【Error】Python:SyntaxError: Non-ASCII character '\xe5'解决办法
- python 有什么 步骤可以知道函数或类在哪个文件定义的
- Python 将数组转换为 Wav
- Python:文件格式不正确
- 如何在 Bash 的 python 解释器中运行 python 脚本
- python-改进脚本和异常处理
- Python(附加列表时出现内存错误)
- Python:另存为字符串时,保存数字错误
- Python:如何编写代码序列?