python中关于元组和字典以及集合的讲解(代码)

#关于元组:
#列表推导式
#字符串中是数字有序序列
#字符串里面的元素是只读的
#和列表比较:列表里面的元素是可以修改的
#字符串为不变类型,相同值指向同一个对象
#节约内存
#比如:
s1="123"
s2="123"
print(id(s1)==id(s2))
#输出:True
a="123adf123dsf44435543xcffgf443545"
a=[b for b in a if b.isdigit()]
print(a)
#输出:['1', '2', '3', '1', '2', '3', '4', '4', '4', '3', '5', '5',
#   '4', '3', '4', '4', '3', '5', '4', '5']

#in和not in 用于判断元素是否在列表内
#a.append()增加
#a.remove()剔除
#list.sort(key,reverse) #key为处理函数 第二个是升序还是降序  True or False
#newls = sorted(a,key,reverse)

#元组采用逗号和圆括号来表示
#通过赋值或tuple()来强制转换
#不可以修改
#用dir()看下tuple对象的方法。
d=2,3
type(d)
d,c=2,3
#主要用于表达固定数据项、函数多返回值return、多变量同步赋值、循环遍历
def fun(x):
    return x,x**3
a,b= 'dog','tiger'#多变量同时赋值,很方便
a,b =(b,a)#可以交换a,b的值,不需要借助第三方
for x,y in ((1,0),(2,5),(3,8)):
    print(x,y)
"""
输出:
1 0
2 5
3 8
"""

#集合:
#集合包含0个或者多个数据项的无序组合,元素不可重复,只能是固定元素。
#集合用大括号{}表示
#如
#也可以用set()函数强制转换,将重复的元素给去除
c = set ("Hello")
print(c)
#集合打印效果与定义顺序可以不一致。如:
print(c)
#成员关系测试 in 或者 not in
#删除数据项
d= c-{"H"}
print(d)
#字典:是映射类型 存放一对一对的,夫妻关系,字典是集合类型的延续,没有重复的元素存在
#每个键只能对应一个只,不允许一键对应多个值

#hash值
hash("hello")

#赋值生成,如
n={"name":"S","age":23}
"""
特殊字符串转字典dt=eval("{"a":5}")有点勉强
推导式生成:

实例:有20个学生,成绩在60--100之间。请筛选出成绩在90分之上的学生
"""
import random
stu = {'student' + str(i):random.randint(60,100) for i in range(20)}
print(stu)
print("------经过筛选之后:------")
stud={name:score for name,score in stu.items() if score > 90}
print(stud)
"""
输出:
{'student0': 60, 'student1': 60, 'student2': 82, 'student3': 77, 
'student4': 70, 'student5': 91, 'student6': 60, 'student7': 82,
 'student8': 84, 'student9': 74, 'student10': 91, 'student11': 63, 
 'student12': 85, 'student13': 68, 'student14': 64, 'student15': 64, 
 'student16': 96, 'student17': 95, 'student18': 92, 'student19': 96}
------经过筛选之后:------
{'student5': 91, 'student10': 91, 'student16': 96, 'student17': 95, 
'student18': 92, 'student19': 96}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值