学习python的第六天(元组、字典和集合操作)

本文详细介绍了Python中的元组、字典和集合的基本操作,包括创建、查找、计数、添加、删除等。通过实例演示了如何使用元组的索引和index方法,字典的键值对查找、添加、删除以及清空操作,并展示了集合的添加、更新和删除元素的方法,以及随机弹出元素的功能。
摘要由CSDN通过智能技术生成
# 定义一个元组
t1 = (10, 12, 13)
print(t1, type(t1))

# 只有一个元素的元组,后面必须要一个逗号
t2 = (12,)
print(t2, type(t2))

# 如果不加逗号,则里面是什么数据类型,整个变量就是什么数据类型
t3 = ("hello")
print(t3, type(t3))

#运行结果

# 元组的查找
t1 = (23, "hu", "湖南")
print(t1[0])
print(t1[1])
print(t1[2])

# index查找 直接查找数据,如果有就返回第一个找到的下标,不存在则报错
print((t1.index(23)))
print((t1.index("hu")))
print((t1.index("湖南")))

# 计数
print(t1.count(23))

#运行结果

 

# 字典的定义
# 特点1,没有顺序
dict1 = {}
dict2 = dict()
print(dict1, type(dict1))
print(dict2, type(dict2))
# 使用大括号 然后以逗号分割 键值对之间使用冒号
# 没有办法通过下标查找,只能通过键 进行查找
dict3 = {"name": "秦晓天", "age": 20, "gender": "man"}
print(dict3, type(dict3))

#运行结果

 

dict1 = {"name": "顺顺", "age": 19}
print(dict1, type(dict1))

# 添加一对键值对
dict1["gender"] = "man"
print(dict1, type(dict1))

# 删除键值对
del dict1["age"]
print(dict1, type(dict1))

# 清空键值对
dict1.clear()
print(dict1, type(dict1))

# 查找 键:值 查找没有的键则报错
dict2 = {"name": "胡某",  "age": 14, "height": 155}
print(dict2["name"])

print(dict2.get("age"))
print(dict2.get("id"))  # 查找没有的键 则返回None
print(dict2.get("id", 100))  # 查找没有的键 则返回默认值

print(dict2.keys(), type(dict2.keys()))  # 返回所有的键 组成一个列表
print(dict2.values(), type(dict2.values()))  # 返回所有的值
# 查找所有的键值对 组成一个列表 里面是每一对键值都是元组
print(dict2.items(), type(dict2.items()))

# 字典的遍历
for key in dict2.keys():  # 遍历键
    print(key)
print("===============")
for value in dict2.values():  # 遍历值
    print(value)
print("===============")
for item in dict2.items():  # 遍历所有的
    print(item)

#运行结果

 

 

 

# 集合是大括号定义 是一个序列
set1 = set()
print(set1, type(set1))

set2 = {1, 2, 3, 4}
print(set2, type(set2))

# 不能直接使用空的大括号定义集合,它本质上是一个字典
set3 = {}

#运行结果

 

set1 = {1, 2, 3, 4, 5, 6}
print(set1)

# 增加数据到集合
set1.add("张三")
print(set1)

# update表示更新数据 集合的特点之一:不能有重复的数据 可以作为去重工具
set1.update([1, 3])
print(set1)

# 会将字符串拆开加入进去,并且发现集合也是没有顺序的
set1.update("abc")
print(set1)

# 删除数据 如果没有该数据则会报错
set1.remove("张三")
print(set1)

# 丢弃一个数据
set1.discard("a")
print(set1)

# 随机弹出一个值
set2 = {34, 3, 5, 4}
result = set2.pop()
print(result)

#运行结果

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值