python基础篇(二)
本文主要涉及到 列表、元组、字典、字符串的用法及各种操作
一、列表
列表是最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作
1.列表定义
>>test_list = ['python','php','shell','ruby'] >>print(type(test_list)) <type 'list'> #可以根据下标来获取列表中的元素 >>>len(test_list) #len 查看列表中有多少个元素 4 >>>test_list[0] 'python' >>>test_list[1] 'php' >>>test_list[2] 'shell' >>>test_list[3] 'ruby' >>>test_list[4] # 会报错,列表中没有那么序号的元素 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range # 会报错,列表中没有那么序号的元素,元素的下标是从0开始的
获取列表中的多个元素: 切片
#切片 >>>test_list = ['python','php','shell','ruby'] >>>test_list[1:3] # 从下标1开始(包含1)到下标3(不包含3) ['php','shell'] >>>test_list[-1:] # 从后面开始 -1是第一个 'ruby' >>>test_list[:2] # 从下标0开始到下标2(不包含2) ['python','php'] >>>test_list[1:] # 从下标1开始(包含1)到后面甩的 ['php','shell','ruby']
2.修改列表
>>>test_list.append('java')
>>>print(test_list)
['python','php','shell','ruby','java']
修改
>>>test_list = ['python','php','shell','ruby'] >>>test_list[1] = 'change_php' >>>test_list ['python','change_php','shell','ruby'] #元素php已经被修改
增加
# 在列表的最后增加
>>>test_list = ['python','php','shell','ruby']
>>>test_list.append('java')
>>>test_list
['python','php','shell','ruby','java]
# 在列表中指定的位置插入
>>>test_list = ['python','php','shell','ruby']
>>>test_list.insert(2,''java) # 2表示列表中的下标,把'java’插入到下标为2的元素前面
>>>test_list
['python','php','java','shell','ruby']
删除
>>>test_list = ['python','php','shell','ruby']
>>> del test_list[1] #删除下标为1的元素
>>>test_list
['python','shell','ruby']
#另一种删除方式
>>>test_list = ['python','php','shell','ruby']
>>>test_list.remove('shell') # 删除指定的元素,而不是下标,这样更方便
>>>test_list
['python','php','ruby']
#还有一种删除方式
>>>test_list = ['python','php','shell','ruby']
>>>test_list.pop() # 删除列表中的最后一个元素
>>>test_list
['python','php','shell']
复制
>>>test_list = ['python','php','shell','ruby'] >>>copy_list = test_list.copy() >>>copy_list ['python','php','shell','ruby'] #这只是浅复制,当列表中嵌套列表时就没有完全复制了
统计
# 统计元素在列表中的个数
>>>test_list = ['python','php','shell','ruby','python']
>>>test_test.count('python')
2
去重
>>> a = [1,2,1,2,3,3,3,2,1,2,4,4] >>> list(set(a)) [1,2,3,4]
获取列表中元素的下标
>>>test_list = ['python','php','shell','ruby','python']
>>>test_list.index('python')
0
二、元组
元组创建后里面的内容是不可更改的,故又叫只读列表
它只有个用法
>>>test = ('php','python','shell','php') >>>type(test) #统计 >>test.count('php') 2 #找出元组里某个值的位置 >>>test.index('python') 1 # 获取无组中的元素 >>> test[test.index('python')] # 获取第一个元素 >>> test[0] # 获取最后一个元素 >>> test[-1]
三、字典
字典是一种key-value的数据类型,在Python语言中唯一的映射类型
# 格式如下:
info = {
'pct01': 'Macbookpro',
'pct02': 'Iphone8',
'pct03': 'bycycle',
'pct04': 'xbox'
}
字典支持增、删、改、查及很多用法
1.增加
# 直接使用上面定义的字典
>>>info
{'pct01': 'Macbookpro', 'pct02': 'Iphone8', 'pct03': 'bycycle', 'pct04': 'xbox'}
>>>info['pct05'] = 'mate9'
>>>info
{'pct01': 'Macbookpro', 'pct02': 'Iphone8','pct05':'mate9', 'pct03': 'bycycle', 'pct04': 'xbox'}
#字典是无序的,每次查询的输出的位置都是可能变的,所以新增加的数据也是无序的插入
2.修改
>>>info['pct04'] = 'Iwatch' >>>info
{'pct01': 'Macbookpro', 'pct04': 'Iwatch','pct05':'mate9', 'pct03': 'bycycle', 'pct02': 'Iphone8'}
3.查询
>>>info
{'pct01': 'Macbookpro', 'pct02': 'Iphone8', 'pct03': 'bycycle', 'pct04': 'xbox'}
>>>'pct02' in info # 只能判断Key
True
>>>info.get('pct04')
'xbox'
# 使用get方法取值,key不存在时会返回none,而不会报错,而使用下面的方式是会报错
>>>info['pct05']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pct05'
4.删除
>>>info
{'pct01': 'Macbookpro', 'pct02': 'Iphone8', 'pct03': 'bycycle', 'pct04': 'xbox'}
# pop用法
>>>info.pop('pct03') #返回的删除key对应的value值
'bycycle'
>>>info
{'pct04': 'xbox','pct01': 'Macbookpro', 'pct02': 'Iphone8'}
# 另一种删除方法
>>>del info['pct04']
>>>info
{'pct01': 'Macbookpro', 'pct02': 'Iphone8'}
# 随机删除
>>>info = {'pct04': 'xbox','pct01': 'Macbookpro', 'pct02': 'Iphone8'}
>>>info.popitem()
('pct01', 'Macbookpro') #被删除的以元组的方式返回
>>>info
{'pct04': 'xbox', 'pct02': 'Iphone8'}
5.其它操作
>>>info = {'pct01': 'Macbookpro', 'pct02': 'Iphone8', 'pct03': 'bycycle', 'pct04': 'xbox'}
# 获取所有的Key
>>>info.keys()
dict_keys(['pct01','pct02','pct03','pct04'])
# 获取所有key的value
>>>info.values()
dict_values(['Macbookpro','Iphone8','bycycle', 'xbox'])
# update
# items
来一个练练手
要求:
1. 打印一个三级菜单
2. 选择可以进行下一级,也可返回上一次
3. 可以随便退出
menu = {
"中国": {
"北京": {
"朝阳": ["国贸", "CBD"],
"海淀": ["百度", "联想"],
"昌平": ["沙河", "十三陵"],
"延庆": ["长城", "旅游"]
},
"上海": {
"浦东": ["陆家嘴", "世博园"],
"闵行": ["莘庄", "紫竹园"],
"黄浦": ["豫园", "小南门"],
"松江": ["欢乐谷", "松江南站"]
}
}
}
flag = True
current = menu
layers = [menu]
while flag is True:
for city in current:
print(city)
city_choose = input("输入地>>>: ")
if city_choose == 'b':
current = layers[-1]
layers.pop()
elif city_choose == 'q':
flag = False
elif city_choose not in current:
continue
else:
layers.append(current)
current = current[city_choose]
四、字符串
字符串是不可修改
# 首字母大写
test.capitalize()
# 大写全部变小写
test.casefold()
# 输出指定格式
test.center(50,'=')
test.ljust(30,'-')
test.rujst(30,'-')
# 统计a出现的次数
test.count('a')
# 将字符串编码成bytes格式
test.encode()
# 判断字符串是否以b结尾
test.endswith('b')
# 判断是否为整数
'10'.isdigit()
#字符串的用法还有很好,其它的可以去网上脑补下
切片
>>> st = 'abcdefg'
>>> type(st)
<type 'str'>
>>> st[0]
'a'
>>> st[1]
'b'
>>> st[2]
'c'
>>> st[:4]
'abcd'
>>> st[3:]
'defg
#分隔
>>> test = 'aa bb cc'
>>> test
'aa bb cc'
>>> test.split(' ') # 以空格为分隔单位
['aa', 'bb', 'cc']
# join用法 (这个好)
>>> test = 'abcdefg'
>>> (','.join(test))
'a,b,c,d,e,f,g'
一个小程序:
- 启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
- 在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
- 用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
- 允许查询之前的消费记录
__author__: cuix
product_list = [
('Macbookpro', '12888'),
('Iphone7', '5888'),
('小米手机6', '2999'),
('自动车', '888'),
('情侣餐', '400'),
('苍井空全集', '299'),
('天猫盒子', '99')
]
buy_list = []
flag = True
# 把文件里的数据转换成字典
user_dict = {}
user_info = open('user_info_file.txt', 'r', encoding='utf-8')
for user in user_info:
user = user.strip()
user_dict[user.split(' ')[0]] = user.split(' ')[1]
user_info.close()
user_name = input("username -->: ").strip()
user_pass = input("userpass -->: ").strip()
if user_name not in user_dict:
user_info = open('user_info_file.txt', 'w', encoding='utf-8')
user_info.write(user_name + ' ' + user_pass)
user_dict[user_name] = int(user_pass)
print("你的用户名-->: \033[31;1m%s\033[0m\n "
"你的密码-->: \033[31;1m%s\033[0m\n"
"\033[32;1m请记住你的用户名和密码以便下次登陆!\033[0m" % (user_name, user_pass))
salary = input("输入你的工资-->: ").strip()
if salary.isdigit():
salary = int(salary)
while flag is True:
for index, product in enumerate(product_list):
print(index, ':', product[0], '-->', product[1])
print("q 退出")
choose = input("\033[33;1m请输入你需要购买的产品编号\033[0m-->: ").strip()
if choose.isdigit():
choose = int(choose)
if choose <= len(product_list) and choose >= 0:
buy_product = product_list[choose]
buy_price = int(buy_product[1])
if salary >= buy_price:
salary -= buy_price
buy_list.append(buy_product)
print("\033[32;1m%s\033[0m 已购入!" % buy_product[0])
print("余额-->: \033[31;1m%s\033[0m" % salary)
else:
print("\033[31;1m你的余额不足!\033[0m")
else:
print("\033[31;1m输入你产品编号不存在!!!\033[0m")
elif choose == 'q':
product_list_file = open('product_list.txt', 'w', encoding='utf-8')
print("------------你购买的产品----------------")
for index, product in enumerate(buy_list):
print(index, ':', product[0], '---', product[1])
product_list_file.write(product[0] + ' ' + product[1] + '\n')
print("你的余额--> \033[31;1m%s\033[0m" % salary)
salary_residue_file = open('salary_residue.txt', 'w')
salary_residue_file.write(str(salary))
product_list_file.close()
salary_residue_file.close()
flag = False
else:
print("\033[31;1m你输入的商品编号不存在!!!\033[0m")
else:
print("\033[31;1m请输入正确的工资!\033[0m")
user_info.close()
else:
if user_dict.get(user_name) == user_pass:
product_list_file = open('product_list.txt', 'r', encoding='utf-8')
salary_residue_file = open('salary_residue.txt', 'r')
salary = int(salary_residue_file.read().strip())
print("--------你购买过的商品-------")
for product in product_list_file:
print(product.strip())
print("你的余额-->: \033[31;1m%s\033[0m\n" % salary)
while flag is True:
for index, product in enumerate(product_list):
print(index, ':', product[0], '-->', product[1])
print("q 退出 p 查询上次的消费")
choose = input("\033[33;1m请输入你需要购买的产品编号\033[0m-->: ").strip()
if choose.isdigit():
choose = int(choose)
if choose <= len(product_list) and choose >= 0:
buy_product = product_list[choose]
buy_price = int(buy_product[1])
if salary >= buy_price:
salary -= buy_price
buy_list.append(buy_product)
print("\033[32;1m%s\033[0m 已购入!" % buy_product[0])
print("余额-->: \033[31;1m%s\033[0m" % salary)
else:
print("\033[31;1m你的余额不足!\033[0m")
else:
print("\033[31;1m输入你产品编号不存在!!!\033[0m")
product_list_file.close()
salary_residue_file.close()
elif choose == 'p':
product_list_file = open('product_list.txt', 'r', encoding='utf-8')
salary_residue_file = open('salary_residue.txt', 'r')
salary = int(salary_residue_file.read().strip())
print("--------你购买过的商品-------")
for product in product_list_file:
print(product.strip())
print("--------你购买过的商品-------\n")
elif choose == 'q':
product_list_file = open('product_list.txt', 'w', encoding='utf-8')
salary_residue_file = open('salary_residue.txt', 'w')
for index, product in enumerate(buy_list):
print(index, ':', product[0], '---', product[1])
product_list_file.write(product[0] + ' ' + product[1] + '\n')
print("你的余额--> \033[31;1m%s\033[0m" % salary)
salary_residue_file.write(str(salary))
flag = False
else:
print("\033[31;1m你输入的商品编号不存在!!!\033[0m")
product_list_file.close()
salary_residue_file.close()
else:
print("\033[31;1m用户名或密码错误!!!\033[0m")
本文主要涉及到 列表、元组、字典、字符串的用法及各种操作
学习的路还很长,坚持。。。
浙公网安备 33010602011771号