首页 > 代码库 > Python中几种数据类型list, tuple,dict,set的使用演示

Python中几种数据类型list, tuple,dict,set的使用演示

还是直接上代码,看着代码运行,看函数介绍

#  coding=utf-8 # 1 list-列表 的用法students = [1,2,3] a = 5classmates = [students*2,[1,1,1,1],[1,1,1,1]]#list的乘法是数组的线性扩大classmates.append(test )         #list的附加classmates.extend(students)        #迭代扩展listprint(classmates.index(test,2))  #list返回制定字符的第一个索引未知classmates.insert(1, 22)           #list插入classmates.pop(2)                  #list项的删除classmates[1] = new item         #list项的 赋值print(classmates )print(classmates[0][1])            #多维数组调用# 2 tuple-元组的用法,元组的值不可变IDcode = (1000,1001,1002)          #定义多元素元组name = (Tom,)                    #定义单元素元组ID_Name = ([1000,Tom],(1001,John),1002)  #定义多维元组,包含元组和list,其中list指向的值可改,元组的不可ID_Name[0][1]=1002print (ID_Name)#3 Dict-数据字典,list不可作为key,但可以作为valuesalary = {Max:1001,Rachel:20001,"Jim111":14000}print(salary[Max])salary[Max] = 2000print(salary[Max])print(salary.pop(Jim,no Jim))print(salary.get(Rachel,-1))print(salary)value = [1,2]salary[Max] = valueprint(salary)#4 set-只有key,没有value,set,Dict的key都不允许可变对象,比如list,只能是字符串或者整数这些不变对象set1 = set([1,2,3])set2 = set([2,3,a])set1.add(4 )set1.remove(2)s =set([sdf,3])print(set1)print(set1&set2,set1|set2)print(set2)#几个函数sort replacedef f(x):    return -ord(x)a1 = [c, b, a]a2 = sdfb=a2.replace(s, a)a1.sort(key=f, reverse=False)print("a is:",a,"\na2 is :",a2,"\nb is",b)

 

Python中几种数据类型list, tuple,dict,set的使用演示