1、元组(Tuple)与列表类似,不同之处在于元组中的元素不能修改
元组表示多个元素组成的序列;元组在Python中,有特定的应用场景
用于存储一组信息、数据之间使用,分隔,元组用()定义,元组的索引从0开始
info_tuple=("zhangsan",18,1.75) print(info_tuple[0]) #1、创建空元组 empty_tuple=() #创建只包含一个元素的元组,需要在元素后面添加逗号 single_tuple=(5,) info_tuple=("zhangsan",18,1.75,"zhangsan") #2、取值和取索引 print(info_tuple[0]) #已知数据的内容,希望知道该数据在元组中的索引 print(info_tuple.index("zhangsan")) #3、统计计数 print(info_tuple.count("zhangsan")) #统计元组中包含元素的个数 print(len(info_tuple))
#4、使用迭代遍历元组 for my_info in info_tuple: #使用格式字符串拼接my_info这个变量不方便,因为元组中通常保存的数据类型不一样 print(my_info) info_tuple=("小明",18,1.75) #5、格式化字符串后面的‘()’本质上就是元组 print("%s年龄是%d,身高是%.2f"%info_tuple) info_str="%s年龄是%d,身高是%.2f"%info_tuple print(info_str) #6、元组和列表转换 list(元组) 元组转列表 tuple(列表) 列表转元组
2、字典
#字典是一个无序的数据集合,使用print函数输出字典时,输出的顺序和定义的顺序是不一致的 xiaoming={"name":"小明", "age":18, "gender446":True, "height":1.75, "weight":75.5} print(xiaoming) xiaoming_dict={"name":"小明"} #1、取值 print(xiaoming_dict["name"]) #2、增加、修改 #如果key不存在,会增加新增键值对;如果key不存在,会修改已经存在的键值对 xiaoming_dict["age"]=18 xiaoming_dict["name"]="小小明" #3、删除 xiaoming_dict.pop("name") print(xiaoming_dict)
#4、统计键值对数量 print(len(xiaoming_dict)) #5、合并字典 #注意:如果被合并的字典中包含已经存在的键值对,会覆盖原有的键值对的值 temp_dict={"height":1.75,"age":20} xiaoming_dict.update(temp_dict) #6、清空字典 xiaoming_dict.clear() print(xiaoming_dict)
#7、迭代遍历字典 xiaoming_dict={"name":"小明","qq":"123456","phone":"10086"} #变量K是每一次循环中,获 取到的键值对的key for k in xiaoming_dict: print("%s-%s"%(k,xiaoming_dict[k]))
#将多个字典放在一个列表里,在进行遍历 card_list=[ {"name":"张三","qq":"12345","phone":"110"}, {"name": "李四", "qq" : "54321", "phone":"10086"} ] for card_info in card_list: print(card_info)