1、创建列表并访问:
names = ["小明", "小红", "小强", "小刚"]
print(names)
print(names[0])
print(names[1:3]) #切片
print(names[:3]) #切片
print(names[-1]) #从右边数,第一个
结果:
['小明', '小红', '小强', '小刚']
小明
['小红', '小强']
['小明', '小红', '小强']
小刚
利用value查找索引
names.index(“小明”)
利用value查找在列表中出现的个数
names.count(“小明”)
跳着输出列表:
print(names[0:-1:2]) 或 print(names[::2])
2、往列表里添加数据
添加在后面:
names.append("小强");
插入数据:
names.insert(1,"小怪")
3、修改直接改变值就可以了
反转数据
names.resverse()
排序方法
names.sort()
4、删除的方法
1、names.remove("小红");
2、del names[0]
3、names.pop() #方法中可以选择删除的下标
4、names.clear() #清除所有
5、复制操作
浅copy
name2 = names.copy() #浅copy,只copy第一层
name2 = copy.copy(names)
name2 = names[:]
name2 = list(names)
深copy
name3 = copy.deepcopy(names) #深copy
6、元组
元组一旦创建,便不能再进行修改,所以又叫只读列表
定义方式:
names = (“person1”, “person2”, “person3”)
7、一个小案例(购物车)
# Author:dancheng
product_list = [
("iphone", 5800),
("Mac Pro", 9800),
("Bike", 800),
("Coffee", 31),
("Alex Python", 120)
]
shop_list = []
salary = input("Input your salary:")
if salary.isdigit() :
salary = int(salary)
while True:
for index,item in enumerate(product_list):
print(index, item)
user_choice = input("choice>>>:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0 :
p_item = product_list[user_choice]
if p_item[1] <= salary: #买的起
shop_list.append(p_item)
salary -= p_item[1]
print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m" %(p_item, salary))
else :
print("money lesser")
else:
print("produce code [%s] is not exist!" %user_choice)
elif user_choice == 'q' :
print("------------shopping list---------------")
for p in shop_list:
print(p)
print("Your current balance:", salary)
exit()
else :
print("invalid option")
else:
exit()