赞
踩
定义一个列表: gege1_list = [“鸡”, “xu”, “2.5” ] 方便后续演示…
list = ['1','2', '3', '4','5']
def while_list():
index = 0
while index < len(list):
print(list[index])
index+=1
def for_list():
for element in list:
print(element)
定义集合输出
my_set = {"坤坤", "爱坤", "爱坤", "爱坤","坤坤", "鸡你太美"}
my_set2 = {}
print(f"my_set的内容是:{my_set},my_set的类型是:{type(my_set)}")
输出结果:可以看到内容无序且唯一:
my_set的内容是:{'坤坤', '鸡你太美', '爱坤'},my_set的类型是:<class 'set'>
my_set.add("python")
print(f"my_set的内容是:{my_set},my_set的类型是:{type(my_set)}")
my_set的内容是:{'python', '鸡你太美', '坤坤', '爱坤'},my_set的类型是:<class 'set'>
set1 = {1,2,3}
set2 = {1,5,6}
set3 = set1.difference(set2)
print(f"set3的内容是:{set3},set3的类型是:{type(set3)}")
set3的内容是:{2, 3},set3的类型是:<class 'set'>
set1 = {1,2,3}
set2 = {1,5,6}
#set3 = set1.difference(set2)
set1.difference_update(set2)
print(f"set1的内容是:{set1},set1的类型是:{type(set1)}")
print(f"set2的内容是:{set2},set2的类型是:{type(set2)}")
输出:
set1的内容是:{2, 3},set1的类型是:<class 'set'>
set2的内容是:{1, 5, 6},set2的类型是:<class 'set'>
set1 = {1,2,3,7}
set2 = {2,1,5,6}
set3 = set1.union(set2)
print(f"set3的内容是:{set3},set3的类型是:{type(set3)}")
输出结果:
set3的内容是:{1, 2, 3, 5, 6, 7},set3的类型是:<class 'set'>
set1 = {1,1,1,1,2,3,7}
print(len(set1))
输出结果:
4
定义:无序Key-Vaule集合,不可以重复,用Key取出Vaule,不可以使用下标索引。
基本语法:my_dict = {key:vaule,key:vaule,key:vaule, key:vaule, … }
空字典:my_dict = {}、my_dict =dict()
定义嵌套字典:
my_dict = {
"坤坤": {"语文":10,"数学":20,"英语":30},
"鸡哥":{"语文":10,"数学":20,"英语":30},
"咯咯哒":{"语文":10,"数学":20,"英语":30}
}
#print(my_dict)
score = my_dict["鸡哥"]["语文"]
print(score)
从嵌套字典中获取数据:
score = my_dict["鸡哥"]["语文"]
print(score)
10
增加:my_dict[“篮球”]=100
修改:my_dict[“篮球”]=60,Key不可以重复,对已存在的Key修改,就是更新。
删除:score = my_dict.pop[“坤坤”]字典被移除了一个元素
清空:my_dic.clear()
获取全部的Keys:my_dic.keys()
my_dict = {
"坤坤": {"语文":10,"数学":20,"英语":30},
"鸡哥":{"语文":10,"数学":20,"英语":30},
"咯咯哒":{"语文":10,"数学":20,"英语":30}
}
number = my_dict.keys()
print(number)
dict_keys(['坤坤', '鸡哥', '咯咯哒'])
遍历字典:
my_dict = {
"坤坤": {"语文":10,"数学":20,"英语":30},
"鸡哥":{"语文":10,"数学":20,"英语":30},
"咯咯哒":{"语文":10,"数学":20,"英语":30}
}
keys = my_dict.keys()
# 第一种遍历
for key in keys:
print(f"字典中的key是:{key}")
print(f"字典中的vaule是:{my_dict[key]}")
# 第二种遍历
for key in my_dict:
print(f"字典中的key是:{key}")
print(f"字典中的vaule是:{my_dict[key]}")
统计字典内的元素个数:num = len(my_dict)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。