一.列表
列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作。
列表切片
names = ["fengxiaoli","Cx","#wang","3bin",["dudu","longlong"],"fengye","Cx"]
print(names[0],names[1])
print(names[0:2])
print(names[:2])
print(names[-1])
print(names[-3:-1])
print(names[-3:])
print(names[0:-1:2]) #0开头,-1结尾,间隔2;0和-1可省
2.打印列表
print(names)
for i in names: #遍历列表中的值
print(i)
3.增加
names.append("chenjia") #从列表最后增加
names.insert(1,"xiaoming") #制定位置增加
print(names)
4.修改
names[1]="daming"
print(names)
5.删除
names.remove("daming") #指定字符删除
names.pop(1) #按索引号删除
names.clear() #删除整个列表
del names[0:3] #指定索引删除
print(names)
6.获取下标
print(names.index("3bin")) #打印3bin所在的下标
print(names[names.index("3bin")]) #打印3bin所在的下标所对应的值
7.其他
names.reverse() #将列表中的值反向
print(names)
print(names.count("Cx")) #统计Cx
names2 = [1,2,3,4]
names.extend(names2) #合并列表names和names2
names.sort() #排序
8.浅复制,深层列表数据和复制前指向同一内存地址
names3 = names.copy()
names[1] = "cxcx" #更改names中数据后,names3只有第一层列表未受影响,二级列表改变,说明二级列表中names和names3指向同一内存地址
names[4][0] = "DUDU"
print(names)
print(names3)
#输出结果
# ['fengxiaoli', 'cxcx', '#wang', '3bin', ['DUDU', 'longlong'], 'fengye', 'Cx']
# ['fengxiaoli', 'Cx', '#wang', '3bin', ['DUDU', 'longlong'], 'fengye', 'Cx']
9.深copy ,列表中所有数据复制到一个新的内存地址,当数据量太大时,慎用
import copy
names = ["fengxiaoli","Cx","#wang","3bin",["dudu","longlong"],"fengye","Cx"]
names3 = copy.deepcopy(names) #copy.copy()也是浅copy
names[1] = "cxcx" #更改names列表中的数据,复制后的names3不受影响
names[4][0] = "DUDU"
print(names)
print(names3)
#输出结果
# ['fengxiaoli', 'cxcx', '#wang', '3bin', ['DUDU', 'longlong'], 'fengye', 'Cx']
# ['fengxiaoli', 'Cx', '#wang', '3bin', ['dudu', 'longlong'], 'fengye', 'Cx']
二.元组
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
它只有2个方法,一个是count,一个是index。
names = ("we","are","chinese","happy","new")
#切片
print(names[0],names[1])
print(names[0:2])
print(names[:2])
print(names[-1])
print(names[-3:-1])
print(names[-3:])
print(names[0:-1:2]) #0开头,-1结尾,间隔2;0和-1可省
三.购物车练习(列表实现)
# Author:fengxiaoli
product_list=[["phone",1000],["bike",500],["computer",2000]]
shop_car=[]
salary=input("Please input your salary:")
if salary.isdigit():
salary=int(salary)
while True:
for index,item in enumerate(product_list):
print(index,item)
shop_choce=input(">>>>>:")
if shop_choce.isdigit():
shop_choce=int(shop_choce)
if shop_choce<=len(product_list)and shop_choce>=0:
temp_shop=product_list[shop_choce]
if salary>=temp_shop[1]:
shop_car.append(temp_shop[0])
salary -=temp_shop[1]
print("\033[31;1mYou bought a %s,Your balance is %s\033[0m"%(temp_shop[0],salary),)
else:
print("\033[31;1mYour balance is not enough\033[0m")
else:
print("\033[31;1mProduct does not exist\033[0m")
elif shop_choce=="q":
print("------Shopping cart list-----")
for i in shop_car:
print(i)
exit()
else:
print(" Invalid input")