python 内置数据结构list、set、dict、tuple(三)

简介: python 内置数据结构list、set、dict、tuple(三)

关于元组的函数

  • 以下看代码
  • 以下函数,对list基本适用
# len:获取元组的长度
t = (1,2,3,4,5)
len(t)
5



# max,min:最大最小值
print(max(t))
print(min(t))
5
1


# tuple:转化或创建元组
l = (1,2,3,4,5)
t = tuple(l)
print(t)

t = tuple()
print(t)
(1, 2, 3, 4, 5)
()

元组的函数

  • 基本跟list通用
# count:计算指定数据出现的次数
t = (2,1,2,3,45,1,1,2,)

print(t.count(2))

# index:求指定元素在元组中的索引位置

print(t.index(45))
# 如果需要的查找的数字是多个,则返回第一个

print(t.index(1))
3
4
1

元组变量交换法

  • 两个变量交换值
# 两个变量交换值
a = 1
b = 3

print(a)
print(b)
print("*" * 20)
# java程序员会这么写:
c = a
a = b
b = c
print(a)
print(b)

print("*" * 20)
# python写法
a,b = b,a
print(a)
print(b)
1
3
********************
3
1
********************
1
3

集合-set

  • 集合是高中数学中的一个概念
  • 一堆确定的无序的唯一的数据,集合中每一个数据成为一个元素
# 集合的定义
s = set()
print(type(s))
print(s)

# 此时,大括号内一定要有值,否则定义出的是一个dict
s = {1,2,3,4,5,6,7}
print(type(s))
print(s)
<class 'set'>
set()
<class 'set'>
{1, 2, 3, 4, 5, 6, 7}


# 如果只是用大括号定义,则定义的是一个dict类型
d = {}
print(type(d))
print(d)
<class 'dict'>
{}

集合的特征

  • 集合的数据无序,即无法使用索引和分片
  • 集合内部数据元素具有唯一性,可以用来排除重复数据
  • 集合内的数据,str,int,float,tuple,冰冻集合等,即内部只能放置可哈希数据

集合序列操作

# 成员检测
# in,not in
s = {4,5,"i", "love", "you"}
print(s)

if "love" in s:
    print("Yes")
    
if "haha" not in s:
    print("Yes")
{'you', 4, 5, 'love', 'i'}
Yes
Yes

集合遍历操作

# for 循环
s = {4,5,"i", "love", "you"}

for i in s:
    print(i)
you
4
5
love
i


# 带有元组的集合遍历
s = {(1,2,3,), ("i", "love", "you"), (4,5,6)}

for k,m,n in s:
    print(k, "--", m, "--", n)
    
for k in s:
    print(k)
i -- love -- you
4 -- 5 -- 6
1 -- 2 -- 3
('i', 'love', 'you')
(4, 5, 6)
(1, 2, 3)

集合的内涵

# 普通集合内涵
# 以下集合在初始化后自动过滤掉重复元素
s = {23,223,233,2,4,5,6,3,4,1,5,3}
print(s)

# 普通集合内涵
ss = {i for i in s}
print(ss)
{1, 2, 3, 4, 5, 6, 233, 23, 223}
{1, 2, 3, 4, 5, 6, 233, 23, 223}


# 带条件的集合内涵
sss = {i for i in s if i % 2 == 0}
print(sss)
{2, 4, 6}


# 多循环的集合内涵
s1 = {1,2,3,4}
s2 = {"i", "love", "you"}

s = {m*n for m in s2 for n in s1}
print(s)

s = {m*n for m in s2 for n in s1 if n == 2}
print(s)
{'you', 'youyou', 'love', 'lovelovelovelove', 'lovelovelove', 'lovelove', 'iii', 'youyouyouyou', 'ii', 'i', 'iiii', 'youyouyou'}
{'lovelove', 'youyou', 'ii'}

集合函数/关于集合的函数

# len,max,min:跟其他基本的函数一致
s = {23,54,72,3,5,3,3,6,1,543}
print(len(s))
print(max(s))
print(min(s))
8
543
1


# set:生成一个集合
l = {1,2,3,4,5,4,3,2,1}
s = set(l)
print(s)
{1, 2, 3, 4, 5}


# add:向集合内添加元素
s = {1}
s.add(3)
print(s)
{1, 3}


# clear
s = {1,2,3,4,5}
print(id(s))
s.clear()
print(id(s))
# 结果表明clear函数是原地清空数据
1370773843528
1370773843528


# copy:拷贝
# remove:移除指定的值,直接改变原有值,如果要删除的值不存在,报错
# discard:移除集合中指定的值跟remove一样,但是如果要删除的话,不报错
s = {23,4,3,5,1,2,3}
s.remove(4)
print(s)
s.discard(1)
print(s)

print("*" * 20)
s.discard(100)
print(s)

s.remove(100)
print(s)
{1, 2, 3, 5, 23}
{2, 3, 5, 23}
********************
{2, 3, 5, 23}



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-35-0113522ad176> in <module>
     12 print(s)
     13 
---> 14 s.remove(100)
     15 print(s)


KeyError: 100


# pop 随机移除一个元素
s = {1,2,3,4,5,6,7}
d = s.pop()
print(d)
print(s)
1
{2, 3, 4, 5, 6, 7}


# 集合函数
# intersection:交集
# difference:差集
# union:并集
# issubset:检查一个集合是否为另一个子集
# issuperset:检查一个集合是否为另一个超集
s1 = {1,2,3,4,5,6}
s2 = {5,6,7,8,9}

s_1 = s1.intersection(s2)
print(s_1)

s_2 = s1.difference(s2)
print(s_2)

s_3 = s1.issubset(s2)
print(s_3)

s_4 = s1.issuperset(s2)
print(s_4)
{5, 6}
{1, 2, 3, 4}
False
False


# 集合数学操作
s1 = {1,2,3,4,5,6}
s2 = {5,6,7,8,9}

# 以下不支持
s_1 = s1 - s2
print(s_1)

s_2 = s1 + s2
print(s_2)
{1, 2, 3, 4}



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-45-fac787d752ea> in <module>
      7 print(s_1)
      8 
----> 9 s_2 = s1 + s2
     10 print(s_2)


TypeError: unsupported operand type(s) for +: 'set' and 'set'

frozen set :冰冻集合

  • 冰冻就是不可以进行任何修改的操作
  • frozenset是一种特殊集合
# 创建
s = frozenset()
print(type(s))
print(s)
<class 'frozenset'>
frozenset()

dict字典

  • 字典是一种组合数据,没有顺序的组合数据,数据以键值对形式出现
# 字典的创建
# 创建空字典1
d = {}
print(type(d))
print(d)

# 创建空字典2
d = dict()
print(d)

# 创建有值的字典,每一组数据用冒号隔开,每一对键值对用逗号隔开
d = {"one":1, "two":2, "three":3}
print(d)

# 用dict创建有内容字典1
d = dict({"one":1, "two":2, "three":3})
print(d)

# 用dict创建有内字典2
# 利用关键参数
d = dict(one=1, two=2, three=3)
print(d)

# 
d = dict( [("one",1), ("two",2), ("three",3)])
print(d)
<class 'dict'>
{}
{}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}


字典的特性

  • 字典是序列类型,但是是无序序列,所以没有分片和索引
  • 字典中的数据每个都有键值对组成,即kv对

    • key:必须是可哈希的值,比如:int,string,float,tuple,但是,list,set,dict不行
    • value:任何值

字典常见操作

# 访问数据
d = {"one":1, "two":2, "three":3}
# 注意访问格式
# 中括号内是键值
print(d["one"])

d["one"] = "eins"
print(d)

# 删除某个操作
# 使用del操作
del d["one"]
print(d)
1
{'one': 'eins', 'two': 2, 'three': 3}
{'two': 2, 'three': 3}


# 成员检测:in,not in
# 成员检测检测时的key内容
d = {"one":1, "two":2, "three":3}

if 2 in d:
    print("value")

if "two" in d:
    print("key")
    
if ("two,2") in d:
    print("kv")
key


# 遍历在python2 和 3 中区别比较大,代码不通用
# 按key值使用for循环
d = {"one":1, "two":2, "three":3}
# 使用for循环,直接按keu值访问
for k in d:
    print(k, d[k])
    
# 上述代码可以改写如下
for k in d.keys():
    print(k, d[k])

# 只访问字典的值
for v in d.values():
    print(v)
    
# 注意以下特殊用法
for k,v in d.items():
    print(k, "--", v)
one 1
two 2
three 3
one 1
two 2
three 3
1
2
3
one -- 1
two -- 2
three -- 3

字典生成式

d = {"one":1, "two":2, "three":3}

# 常规字典生成式
dd = {k:v for k,v in d.items()}
print(dd)

# 加限制条件的字典生成式
dd = {k:v for k,v in d.items() if v % 2 == 0}
print(dd)
{'one': 1, 'two': 2, 'three': 3}
{'two': 2}

字典相关函数

# 通用函数:len,max,min,dict
# str(字典):用于返回字典的字符串格式
d = {"one":1, "two":2, "three":3}
print(str(d))
{'one': 1, 'two': 2, 'three': 3}


# clear:清空字典
# items:返回字典的键值对组成的元组格式

d = {"one":1, "two":2, "three":3}
i = d.items()
print(type(i))
print(i)
<class 'dict_items'>
dict_items([('one', 1), ('two', 2), ('three', 3)])


# keys:返回字典的键组成的一个结构
k = d.keys()
print(type(k))
print(k)
<class 'dict_keys'>
dict_keys(['one', 'two', 'three'])


# values:同理,一个可迭代的结构
v = d.values()
print(type(v))
print(v)
<class 'dict_values'>
dict_values([1, 2, 3])


# get:根据指定键返回相应的值,好处是,可以生成默认值

d = {"one":1, "two":2, "three":3}
print(d.get("oner"))

# get默认值是None,可以设置
print(d.get("one", 100))
print(d.get("one33", 100))

print(d['on333'])
None
1
100



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-86-f8c01a58018e> in <module>
      8 print(d.get("one33", 100))
      9 
---> 10 print(d['on333'])


KeyError: 'on333'


# fromkeys:使用指定的序列作为键,使用一个值作为字典的所有键的值
l = ["eins", "zwei", "dree"]
# 注意fromkeys两个参数的类型
# 注意fromkeys的调用主体
d = dict.fromkeys(l, "hahahahaha")
print(d)
{'eins': 'hahahahaha', 'zwei': 'hahahahaha', 'dree': 'hahahahaha'}
目录
相关文章
|
1天前
|
JSON 数据可视化 Shell
数据结构可视化 Graphviz在Python中的使用 [树的可视化]
数据结构可视化 Graphviz在Python中的使用 [树的可视化]
8 0
|
4天前
|
Python
【Python 基础】列表(list)和元组(tuple)有什么区别?
【5月更文挑战第6天】【Python 基础】列表(list)和元组(tuple)有什么区别?
|
4天前
|
存储 索引 Python
python数据结构知识学习
【5月更文挑战第6天】Python提供四种核心数据结构:列表(List)——可变有序集合,支持索引和切片;元组(Tuple)——不可变有序集合;字典(Dictionary)——键值对结构,通过键访问值;集合(Set)——无序不重复元素集合,支持数学运算。此外,Python允许自定义数据结构,如链表、树、图,以适应不同问题需求。
13 0
|
4天前
|
存储 C++ 容器
[数据结构]-map和set
[数据结构]-map和set
|
15天前
|
存储 NoSQL Redis
Redis入门到通关之Redis数据结构-Set篇
Redis入门到通关之Redis数据结构-Set篇
20 1
|
15天前
|
存储 NoSQL Java
Redis入门到通关之数据结构解析-Dict
Redis入门到通关之数据结构解析-Dict
19 2
|
17天前
|
存储 索引 Python
多数pythoneer只知有列表list却不知道python也有array数组
多数pythoneer只知有列表list却不知道python也有array数组
26 0
|
21天前
|
存储 数据挖掘 Serverless
Python推导式:简洁高效的数据结构构建与应用
【4月更文挑战第4天】Python的推导式是其简洁语法的体现,包括列表、字典、集合和生成器推导式。本文介绍了各种推导式的使用,例如通过列表推导式生成平方数列表,字典推导式创建数字与平方的映射,集合推导式得到奇数集合,以及生成器推导式实现懒加载。此外,还讲解了嵌套推导式、条件表达式、性能考虑、数据过滤和转换、与函数结合、灵活运用和错误处理等。推导式在文件处理、多层嵌套数据结构、字典操作、数据分析、异步编程等场景中都有应用,但过度使用可能降低可读性,需根据情况权衡。
49 4
|
24天前
|
算法 搜索推荐 Python
数据结构与算法在Python面试中的应用实例
【4月更文挑战第13天】本文聚焦Python面试中的数据结构与算法问题,包括排序算法、链表操作和树图遍历。重点讨论了快速排序、链表反转和二叉树前序遍历的实现,并指出理解算法原理、处理边界条件及递归操作是避免错误的关键。通过实例代码和技巧分享,帮助面试者提升面试表现。
13 0
|
24天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
69 0