6day
列表练习:
1、创建一个空列表,命名为names,往里面添加old_drilver,rain,jack,shanshan,peiqi,black_girl;
names = []
names.append('old_driver')
......
names = ['old_driver','rain','jack','shanshan','peiqi','black_girl']
2、在names列表里面black_girl前面插入一个alax;
names.insert(5,'alax')
names = ['old_driver', 'rain', 'jack', 'shanshan', 'peiqi', 'alax', 'black_girl']
3、往names列表里rain后面插入一个子列表,[oldboy,oldgirl]
namse.insert(2,['oldboy','oldgirl'])
4、循环names列表,打印每个元素的索引值,和元素;
names=['old_driver','rain',['oldboy','oldgirl'],'jack','shanshan','peiqi','black_girl']
for i in names:
print(names.index(i),i)
5、循环names列表,打印每个元素的索引值,和元素。当索引值为偶数时,把对应的元素改为-1;
names=['old_driver','rain',['oldboy','oldgirl'],'jack','shanshan','peiqi','black_girl']
for i in names:
if names.index(i)%2 == 0:
names[names.index(i)] = -1
print(names)
6、names列表里面有3个2,请返回第2个2的索引值。不要人肉书,要动态找;
names=['old_driver',2,'rain',['oldboy','oldgirl'],2,'jack','shanshan','peiqi',2,'black_girl']
fisrt_index = names.index(2) #第一个2的索引
new_list = names[fisrt_index+1:] #将第一个2后面的列表切片
second_index = new_list.index(2) #在新的列表中找到第二个2的索引
second_val = names[fisrt_index+second_index+1] #第二个2在names列表中的索引等于第一个2索引和第二个2索引+1
print("second val:",second_val )
7、
products = [['Iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Booke',80],['Nike Shoes',799]]
print("--------商品列表---------")
for index,i in enumerate(products):
print("%s. %s %s" %(index,i[0],i[1]))
products = [['Iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Booke',80],['Nike Shoes',799]]
cart = []
print("--------商品列表---------")
while True:
for index,i in enumerate(products):
print("%s. %s %s" %(index,i[0],i[1]))
choice = input("请输入你想购买的商品编号:")
if choice.isdigit():
choice = int(choice)
if choice>0 and choice < len(products):
cart.append(products[choice])
print("你已购买 %s 商品!"%(products[choice]))
else:
print("商品不存在!")
elif choice == 'q':
print("---------你已购买以下商品----------")
if len(cart) > 0:
for index, i in enumerate(cart):
print("%s. %s %s" % (index, i[0], i[1]))
break