新知识元组、字典
元组:也可以把它看成一个列表,但不同的是元组内的数据是不可以修改的,是固定的,只能加入和查找。
上图片!!!
?
改动操作会出错:
#改动不可以
tup1=("2020","2021","2022")
tup1[0]=2023
输出结果:
Traceback (most recent call last):
File "C:/Users/汘际/PycharmProjects/元组/main.py", line 3, in <module>
tup1[0]=2023
TypeError: 'tuple' object does not support item assignment
不支持删除
元组增加操作: tup=tup1+tup2
#增加,新结构,增加空间
tup1=(2021,2022)
tup2=("年","快","乐")
tup=tup1+tup2
print(tup)
输出结果:
(2021, 2022, '年', '快', '乐')
元组的+操作是结构的扩张,内容的扩张不是代数运算
元组的清空操作:del? ?注意与删除某一个元素区分。
#s删除操作,能够将元祖全部删除
tup=(2021,2022,2023)
print(tup)
del tup
print(tup)
结果:
(2021, 2022, 2023)
Traceback (most recent call last):
File "C:/Users/汘际/PycharmProjects/元组/main.py", line 18, in <module>
print(tup)
NameError: name 'tup' is not defined
未声明,说明已经将整个元组删除
字典\键值对:一个键对应一个值,键是唯一的,但是值可以是相同的。比如info={"name":"giao","age",40},不同的键值对用,隔开,一个键值对格式是? ? "a":"b"
元组的插入:
info={"name":"封瑶","age":18}
newID=input("请输入你的学号")
info["id"]=newID
print(info["id"])
结果:
请输入你的学号1
1
字典?的删除:1.del?将整个键删除? 2.将整个字典清空
1.del
# 删除
# del功能
info={"name":"封瑶","age":18}
print("删除前:%s"%info["name"])
del info["name"]
#删除了指定键值对,不单单是值
print("删除后:%s" % info["name"])
输出结果
删除前:封瑶
Traceback (most recent call last):
File "C:/Users/汘际/PycharmProjects/字典/main.py", line 13, in <module>
print("删除后:%s" % info["name"])
KeyError: 'name'
name的这个不存在
删除整个字典
info={"name":"封瑶","age":18}
del info
print("删除后:%s" % info)
结果:
Traceback (most recent call last):
File "C:/Users/汘际/PycharmProjects/字典/main.py", line 17, in <module>
print("删除后:%s" % info)
NameError: name 'info' is not defined
未声明,删除成功
2.clear功能:清空字典里面的所有键值,剩一个{},为空
clear清空操作
info={"name":"封瑶","age":18}
info.clear()
print("清空后:%s" % info)
输出结果:
清空后:{}
字典的修改操作:
info={"name":"封瑶","age":18}
info["age"]=20
print(info["age"])
输出结果:
20
字典的查找操作:
info={"id":1,"name":"封瑶","age":18}
print(info.keys()) #得到所有键
print(info.values())#得到所有值
print(info.items())#得到每一项
打印结果:
dict_keys(['id', 'name', 'age'])
dict_values([1, '封瑶', 18])
dict_items([('id', 1), ('name', '封瑶'), ('age', 18)])
字典的遍历:
字典分为键和值,可以对2者分别遍历,或者合起来遍历。
对键遍历
info={"id":1,"name":"封瑶","age":18}
for key in info.keys():
print(key)
输出结果:
id
name
age
对值遍历
for values in info.values():
print(values)
输出结果:
1
封瑶
18
对键值遍历
for key,value in info.items():
print("key=%s,value=%s"%(key,value))
输出结果:
key=id,value=1
key=name,value=封瑶
key=age,value=18
进程已结束,退出代码为 0
Today, I mainly studied the knowledge about tuples and dictionaries and basic operations, and understood the characteristics between them.?For example, tuples cannot modify elements arbitrarily, whereas dictionaries are composed of one key for each value. The key must be different, and the value may be the same.?On the whole, it was a good harvest
|