python数据类型元组、字典、集合

元组

python的元组与列表类似,不同的是元组是不可变的数据类型。元组使用小括号,列表使用方括号。当元组里只有一个元素是必须要加逗号:

  1. >>> x = (1,)
  2. >>> type(x)
  3. <class 'tuple'>
  4. >>> y =(1)
  5. >>> type(y)
  6. <class 'int'>
  7. >>> z = 1,
  8. >>> type(z)
  9. <class 'tuple'>
  10. >>> z = 1,2
  11. >>> type(z)
  12. <class 'tuple'>
  13. >>>

元组的特性:

  • 不可变

  • 可存放多个值

  • 按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序

元组创建

元组创建可以直接在括号里添加元素,也可以直接逗号赋值创建,还可以使用tuple函数,默认创建就是去调用tuple函数:

  1. >>> tup1 = {'tom','jack','rain'}
  2. >>> tup1 = ('tom','jack','rain')
  3. >>> tup2 = (1,2,3,4,5)
  4. >>> tup3 = 'a','b','c','d'
  5. >>> type(tup1)
  6. <class 'tuple'>
  7. >>> type(tup2)
  8. <class 'tuple'>
  9. >>> type(tup3)
  10. <class 'tuple'>
  11. >>>
  12. >>>> m = ['a','b','c']
  13. >>> n = tuple(m)
  14. >>> n
  15. ('a', 'b', 'c')
  16. >>>

创建空元组:

  1. >>> tup = ()
  2. >> type(tup)
  3. <class 'tuple'>
  4. >>>

元组常用操作

索引和切片:

  1. >>> x=(1,2,3,4,5)
  2. 1
  3. >>> x[::-1]
  4. (5, 4, 3, 2, 1)
  5. >>> x[-2:]
  6. (4, 5)
  7. >>> x[::2]
  8. (1, 3, 5)
  9. >>>

循环:

  1. >>> x=(1,2,3,4,5)
  2. >>> for i in x:
  3. print(i)
  4. 1
  5. 2
  6. 3
  7. 4
  8. 5
  9. >>>

长度:

  1. >>> x=(1,2,3,4,5)
  2. >>> len(x)
  3. 5
  4. >>>

成员运算(包含)

  1. >>> x=(1,2,3,4,5)
  2. >>> 1 in x
  3. True
  4. >>> '1' in x
  5. False
  6. >>>

字典

定义:{key1:value1,key2:value2},key-value结构,key必须可hash,即是key必须是不可变类型:

字典的特性:

  • 可存放多个值(键值对items)
  • 可修改指定key对应的值,可变
  • 无序

字典创建

person = {"name": "lucy", 'age': 18}



person = dict(name='lucy', age=18)

person = dict({"name": "lucy", 'age': 18})

person = dict((['name','lucy'],['age',18]))

person = dict((('name','bob'),('age',18)))

{}.fromkeys(seq,100) #不指定100默认为None

注意:

  1. >>> dic={}.fromkeys(['k1','k2'],[])
  2. >>> dic
  3. {'k1': [], 'k2': []}
  4. >>> dic['k1'].append(1)
  5. >>> dic
  6. {'k1': [1], 'k2': [1]}

字典常用操作

索引

因为字典是无序的,所以访问字典的值是通过键值来索引访问。

  1. >>> dict1 = {'name': 'bob', 'age': 16, 'gender': 'male'}
  2. >>> dict1['name']
  3. 'bob'
  4. >>> dict1['age']
  5. 16

但是当输入的索引键在字典中没有会报错:

  1. >>> dict1 = {'name': 'bob', 'age': 16, 'gender': 'male'}
  2. >>> dict1['Age']
  3. Traceback (most recent call last):
  4. File "<pyshell#110>", line 1, in <module>
  5. dict1['Age']
  6. KeyError: 'Age'

程序里我们可以使用get()去访问字典中的值,即使键值字典里没有也不会报错。找到了就返回value,找不到默认不返回任何信息,可以自定义返回信息内容

  1. >>> dict1 = {'name': 'bob', 'age': 16, 'gender': 'male'}
  2. >>> dict1.get('Age')
  3. >>>
  4. >>> dict1.get('Age',-1)
  5. -1
  6. >>> dict1.get('Age','找不到')
  7. '找不到'
  8. >>> dict1.get('age')
  9. 16
  10. >>>

新增和更新

增加items只需要直接赋值即可,更新也是一样的:

  1. >>> d1 = {}
  2. >>> d1['name'] = 'tom'
  3. >>> d1['age'] = 18
  4. >>> d1
  5. {'name': 'tom', 'age': 18}
  6. >>> d1['age'] = 20
  7. >>> d1
  8. {'name': 'tom', 'age': 20}
  9. >>>

删除

del删除不会返回任何信息,删除键值不存在的会报错。

  1. >>> d1
  2. {'name': 'tom', 'age': 20}
  3. >>> del d1['age']
  4. >>> d1
  5. {'name': 'tom'}
  6. >>> del d1['Age']
  7. Traceback (most recent call last):
  8. File "<pyshell#124>", line 1, in <module>
  9. del d1['Age']
  10. KeyError: 'Age'
  11. >>>

pop()删除和popitem()

pop()删除字典给定键 key 所对应的值,返回值为被删除的值。

  1. >>> d1 = {'name': 'tom', 'age': 18}
  2. >>> d1
  3. {'name': 'tom', 'age': 18
  4. >>> d1.pop('age')
  5. 18
  6. >>> d1
  7. {'name': 'tom'}
  8. >>>

popitem()随机返回并删除字典中的一对键和值

  1. >>> d1 = {'name': 'tom', 'age': 18}
  2. >>> d1.popitem()
  3. ('age', 18)
  4. >>>

循环

  1. dict1 = {'name':'tom','age':20,'gender':'male','hobbie':'music'}
  2. for i in dict1:
  3. print(i)

运行结果:

name

age

gender

hobbie

for i in 字典 和 for i in 字典.keys()是一样的作用,都是遍历字典的键。

for i in 字典.items() 可以循环遍历字典的键值对:

  1. dict1 = {'name':'tom','age':20,'gender':'male','hobbie':'music'}
  2. for i in dict1.items():
  3. print(i)

运行结果:

('name', 'tom')

('age', 20)

('gender', 'male')

('hobbie', 'music')

  1. dict1 = {'name':'tom','age':20,'gender':'male','hobbie':'music'}
  2. for k,v in dict1.items():
  3. print('dict1[%s]=%s' %(k,v))

运行结果:

dict1[name]=tom

dict1[age]=20

dict1[gender]=male

dict1[hobbie]=music

长度

  1. >>> d1 = {'name': 'tom', 'age': 18}
  2. >>>> len(d1)
  3. 2
  4. >>> len(d1.keys())
  5. 2
  6. >>> len(d1.values())
  7. 2
  8. >>>

集合

set是基本数据类型的一种集合类型,是一个无序不重复元素集。它有可变集合(set())和不可变集合(frozenset)两种。创建集合set、集合set添加、集合删除、交集、并集、差集的操作都是非常实用的方法。

集合的创建

创建一个数组集合:

  1. >>> s1 = set([1,3,5,7,8])
  2. >>> type(s1)
  3. <class 'set'>
  4. >>> s1
  5. {1, 3, 5, 7, 8}
  6. >>>

创建字符集合:

  1. >>> s2 = set('Hello')
  2. >>> type(s2)
  3. <class 'set'>
  4. >>> s2
  5. {'l', 'H', 'e', 'o'}
  6. >>>

上面的字符集合,里面只有一个'l'

集合常用操作

交集,并集,差集,对称差集

a = t | s        # t 和 s的并集

b = t & s        # t 和 s的交集

c = t – s        # 求差集(项在t中,但不在s中)

d = t ^ s        # 对称差集(项在t或s中,但不会同时出现在二者中)

添加

添加一项:

  1. >>> s1 = set([1,3,5,7,8])
  2. >>> s1.add(10)
  3. >>> s1
  4. {1, 3, 5, 7, 8, 10}
  5. >>>

添加多项:

  1. >>> s1 = set([1,3,5,7,8])
  2. >>> s1.update([11,12,13])
  3. >>> s1
  4. {1, 3, 5, 7, 8, 11, 12, 13}
  5. >>>

删除

删除一项,如果果不存在则报错,不报错可以使用discard(),discard删除元素,如果集合中有这个元素就删除,没有也不会报错。pop()随机删除集合的一个元素,返回值为随机删除的元素,集合为空时pop()会报错。 删除整个集合使用clear()

  1. >>> s1 = {1, 3, 5, 7, 8,13}
  2. >>> s1
  3. {1, 3, 5, 7, 8, 13}
  4. >>> s1.remove(13)
  5. >>> s1
  6. {1, 3, 5, 7, 8}
  7. >>> s1.remove(14)
  8. Traceback (most recent call last):
  9. File "<pyshell#172>", line 1, in <module>
  10. s1.remove(14)
  11. KeyError: 14
  12. >>> s1.discard(14)
  13. >>> s1.discard(13)
  14. >>> s1.discard(8)
  15. >>> s1
  16. {1, 3, 5, 7}

长度

集合的长度:

  1. >>> s1 = {1, 3, 5, 7, 8,13}
  2. >>> len(s1)
  3. 6
  4. >>>

成员运算

  1. >>> s1 = {1, 3, 5, 7, 8,13}
  2. >>> 5 in s1
  3. True
  4. >>> '5' in s1
  5. False
  6. >>>

子集

  1. >>> s1 = {'a','b','c'}
  2. >>> s2 = {'a','b','c','d'}
  3. >>> s1.issubset(s2)
  4. True
  5. >>>

父集

  1. >>> s1 = {'a','b','c'}
  2. >>> s2 = {'a','b','c','d'}
  3. >>> s2.issuperset(s1)
  4. True
  5. >>>

交集

等价于 s1 & s2

  1. >>> s1 = {'a','b','c','d'}
  2. >>> s2 = {'a','c','e','f'}
  3. >>> s1.intersection(s2)
  4. {'c', 'a'}

并集

等价于 s1 | s2

  1. >>> s1 = {'a','b','c','d'}
  2. >>> s2 = {'a','c','e','f'}
  3. >>> s1.union(s2)
  4. {'b', 'e', 'd', 'c', 'f', 'a'}
  5. >>>

差集

等价于 s1 - s2

  1. >>> s1 = {'a','b','c','d'}
  2. >>> s2 = {'a','c','e','f'}
  3. >>> s1.difference(s2)
  4. {'b', 'd'}
  5. >>>

对称差集

等价于 s1 ^ s2

  1. >>> s1 = {'a','b','c','d'}
  2. >>> s2 = {'a','c','e','f'}
  3. >>> s1.symmetric_difference(s2)
  4. {'b', 'f', 'e', 'd'}
  5. >>>

python数据类型之元组、字典、集合的更多相关文章

  1. **python中列表 元组 字典 集合

    列表 元组 字典 集合的区别是python面试中最常见的一个问题.这个问题虽然很基础,但确实能反映出面试者的基础水平. 1.列表 列表是以方括号“[]”包围的数据集合,不同成员以“,”分隔. 列表的特 ...

  2. python中列表 元组 字典 集合的区别

    列表 元组 字典 集合的区别是python面试中最常见的一个问题.这个问题虽然很基础,但确实能反映出面试者的基础水平. (1)列表 什么是列表呢?我觉得列表就是我们日常生活中经常见到的清单.比如,统计 ...

  3. 5. Python数据类型之元组、集合、字典

    元组(tuple) 元组创建很简单,只需要在小括号中添加元素,并使用逗号隔开即可.与列表不同的是,元组的元素不能修改.如下代码所示: tup1 = () tup2 = (1) tup3 = (1,) ...

  4. python的学习笔记01_4基础数据类型列表 元组 字典 集合 其他其他(for,enumerate,range)

    列表 定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素 特性: 1.可存放多个值 2.可修改指定索引位置对应的值,可变 3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问 ...

  5. python 中列表 元组 字典 集合的区别

    先看图片解释 (1)列表 什么是列表呢?我觉得列表就是我们日常生活中经常见到的清单.比如,统计过去一周我们买过的东西,把这些东西列出来,就是清单.由于我们买一种东西可能不止一次,所以清单中是允许有重复 ...

  6. python的列表元组字典集合比较

    定义 方法 列表 可以包含不同类型的对象,可以增减元素,可以跟其他的列表结合或者把一个列表拆分,用[]来定义的 eg:aList=[123,'abc',4.56,['inner','list'],7- ...

  7. python 深浅拷贝 元组 字典 集合操作

    深浅拷贝 :值拷贝 :ls = [,,] res = ls 则print(res)就是[,,] 浅拷贝 :ls.copy() 深拷贝:ls3 = deepcopy(ls) # 新开辟列表空间,ls列表 ...

  8. python3笔记十八:python列表元组字典集合文件操作

    一:学习内容 列表元组字典集合文件操作 二:列表元组字典集合文件操作 代码: import pickle  #数据持久性模块 #封装的方法def OptionData(data,path):    # ...

  9. Python数据类型详解——字典

    Python数据类型详解--字典 引子 已经学习了列表,现在有个需求--把公司每个员工的姓名.年龄.职务.工资存到列表里,你怎么存? staff_list = [ ["Kwan", ...

  10. 元组/字典/集合内置方法+简单哈希表(day07整理)

    目录 二十三.元组内置方法 二十四.字典数据类型 二十五 集合内置方法 二十五.数据类型总结 二十六.深浅拷贝 补充:散列表(哈希表) 二十三.元组内置方法 什么是元组:只可取,不可更改的列表 作用: ...

随机推荐

  1. Sql的基础知识技巧(三)

    三.技巧 1.1=1,1=2 的使用,在 SQL 语句组合时用的较多 "where 1=1" 是表示选择全部 "where 1=2"全部不选, 如:if @st ...

  2. TCP/IP(六)应用层(DNS和HTTP协议)

    前言 到这一篇我已经把TCP/IP五层模型详细的说明了一遍,大体的从物理层到最上层的应用层做了一个大概的了解,其实总体学下来东西非常的多,我们需要经常的去系统性的去学习它.不然过一段时间就忘记了! 回 ...

  3. set使用实例1+lower_bound(val)(个人模版)

    set使用实例1+lower_bound(val): #include<stdio.h> #include<set> #include<iostream> #inc ...

  4. Codeforces Round #409 (rated, Div. 2, based on VK Cup 2017 Round 2)(A.思维题,B.思维题)

    A. Vicious Keyboard time limit per test:2 seconds memory limit per test:256 megabytes input:standard ...

  5. C++课程设计类作业4

    #include <bits/stdc++.h> using namespace std; class xiexin { public: xiexin() { weight=; grade ...

  6. XYZZY(spfa求最长路)

    http://acm.hdu.edu.cn/showproblem.php?pid=1317 XYZZY Time Limit: 2000/1000 MS (Java/Others)    Memor ...

  7. 找出单链表中倒数第K个元素

  8. [国嵌攻略][104][Linux内核模块设计]

    内核模块示例 #inlcude <linux/init.h> #inlcude <linux/module.h> static int hello_init(){ printk ...

  9. 算法-java代码实现希尔排序

    希尔排序 第8节 希尔排序练习题 对于一个int数组,请编写一个希尔排序算法,对数组元素排序. 给定一个int数组A及数组的大小n,请返回排序后的数组.保证元素小于等于2000. 测试样例: [1,2 ...

  10. win7、win10进程pid4占用80端口的解决办法

    https://jingyan.baidu.com/article/7e4409533ffe092fc1e2ef10.html 今天想用wamp架设服务器,但是程序启动不起来,查看系统端口,80端口被 ...