python基础—day5 列表
1.列表的创建与删除
序列是 Python 中最基本的数据结构。
序列中的每个值都有对应的位置值,称之为索引,第一个索引是 0,第二个索引是 1,依此类推。
列表的数据项不需要具有相同的类型
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
或者用内置函数list创建。
list1 = list('red', 'green', 'blue', 'yellow', 'white', 'black')
创建空列表
Lst = []
删除列表对象
Del lst
2列表的特性
1、有序的集合
2、通过偏移来索引,从而读取数据
3、支持嵌套
4、可变的类型
3列表中的索引
获取列表中元素的索引
list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[0] )
print( list[1] )
print( list[2] )
red
green
blue
#索引也可以从尾部开始,最后一个元素的索引为 -1,往前一位为 -2,以此类推。
list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[-1] )
print( list[-2] )
print( list[-3] )
black
white
yellow
获取列表中指定元素的索引
#index() 函数用于从列表中找出某个值第一个匹配项的索引位置
#list.index(x[, start[, end]])
list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print(list.index('red'))
0
获取列表中多个元素(切片)
lst1=[1,2,3,4,5,6,7,8,9]
#print(lst[1:6:1])
#[2, 3, 4, 5, 6]
lst2=lst1[1:6]
#切出来的对象是由原列表复制出来的新对象
print('原列表',id(lst1))
print('切的片断',id(lst2))
原列表 1659400
切的片断 1659912
#步长为负数的时候
lst1=[1,2,3,4,5,6,7,8,9]
print(lst1[::-1])
#[9, 8, 7, 6, 5, 4, 3, 2, 1]
print(lst1[7::-1])
#[8, 7, 6, 5, 4, 3, 2, 1]
print(lst1[8:0:-2])
#[9, 7, 5, 3]
列表元素的判断和遍历
lst =['hello',10,20,'world']
print(10 in lst)
True
print(30 in lst)
False
for i in lst:
print(i)
hello
10
20
world
列表元素的增删改操作
list.append(obj) #append() 方法用于在列表末尾添加新的对象。
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)
#更新后的列表 : ['Google', 'Runoob', 'Taobao', 'Baidu']
list2 = ['Pingduoduo','Jingdong']
list1.append(list2)
print(list1)
#['Google', 'Runoob', 'Taobao', 'Baidu', ['Pingduoduo', 'Jingdong']]
list.extend(在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list1.extend(list2)
print(list1)
['Google', 'Runoob', 'Taobao', 'Baidu', 'Pingduoduo', 'Jingdong']
insert() 函数用于将指定对象插入列表的指定位置。
list1 = ['Google', 'Runoob', 'Taobao']
list1.insert(1, 'Baidu')
print ('列表插入元素后为 : ', list1)
#列表插入元素后为 : ['Google', 'Baidu', 'Runoob', 'Taobao']
购物车
1.输入客户金额
2.显示购物信息
3.输入购物信息
4.返回已购物内容及剩余金额
#__user:__Mlly
# date : 2021/5/24
'''1.显示购物信息
2.输入客户金额
3.输入购物信息
4.返回已购物内容及剩余金额'''
#商品信息
goods = [('book',100),
('phone',2000),
('tea',500),
('bag',1000),
('bike',2000)
]
#输入你的金额
moeny = input('你有多少钱:')
moeny = int(moeny)
goods_car = []
flag =True
while flag:
#展示商品信息
for i,v in enumerate(goods):#问我也还不知道,enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
print(i,'>>>',v)
#输入想购买的商品
need_goods = int(input('你想购买的序号:'))
#判断是否可以购买
if moeny > goods[need_goods][1]:
#将商品信息加入购物车并输出购物车及余额
goods_car.append(goods[need_goods])
moeny -= goods[need_goods][1]
print('你已购买{},你的余额为{}'.format(goods_car,moeny))
choice = input('是否继续购买y/n:')
if choice == 'y':
continue
else:
flag =False
else:
print('你的余额不足')
print('你已购买{}'.format(goods_car))
break

浙公网安备 33010602011771号