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

时间:2022-06-21 09:12:53

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

#  coding=utf-8
# 1 list-列表 的用法
students = [1,2,3]
a = 5
classmates = [students*2,[1,1,1,1],[1,1,1,1]]#list的乘法是数组的线性扩大
classmates.append('test' )         #list的附加
classmates.extend(students)        #迭代扩展list
print(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]=1002
print (ID_Name)

#3 Dict-数据字典,list不可作为key,但可以作为value
salary = {'Max':1001,'Rachel':20001,"Jim111":14000}
print(salary['Max'])
salary['Max'] = 2000
print(salary['Max'])
print(salary.pop('Jim','no Jim'))
print(salary.get('Rachel',-1))
print(salary)
value = [1,2]
salary['Max'] = value
print(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)   #set 的交、并运算
print(set2)

#几个函数sort replace
def f(x):
    return -ord(x)
a1 = ['c', 'b', 'a']
a2 = 'sdf'
b=a2.replace('s', 'a')
a1.sort(key=f, reverse=False)
print("a is:",a,"\na2 is :",a2,"\nb is",b)