字符串列表元组字典参数
Posted 王晓冬
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串列表元组字典参数相关的知识,希望对你有一定的参考价值。
python_two_day |
作者:_晓冬 归档:学习笔记 2016/9/16
|
目 录
第1章... 1
1.1 可变和不可变类型... 1
第2章 字符串类型... 1
2.1 【重点】字符串取值方法... 1
2.2 【了解】字符串方法... 1
2.3 练习题... 2
2.4 打破顺序位置占位... 3
2.5 辨别find,rfind,index,rindex,ocunt 3
2.6 判断数字... 4
第3章 列表类型... 5
3.1 其他操作... 7
第4章 元组... 10
4.1 循环元组... 11
4.2 字典... 12
4.3 注意:设计数据结构的根本目的是方便自己的存和取... 13
4.4 两种赋值方式... 13
4.5 集合... 17
4.6 去重并定序... 19
第1章
1.1 可变和不可变类型
注意:当数值量较小时定义变量指向同一块内存空间
x=123
y=123
print(id(x))
print(id(y))
字符串也是一样样的
第2章 字符串类型
2.1 【重点】字符串取值方法
l 按照索引取值
l 按照切片取值
l 字符串长度计算:len
l 成员运算 :in 和 not in
l 移除空白strip
l 切分split
l 循环
2.2 【了解】字符串方法
l .replace :替换
例:
msg=‘alex say i have one telsa,my name is alec‘
print(msg.replace(‘alex‘,‘Sb‘,1))
C:\python3\python.exe D:/python/untitled/two_day.py
Sb say i have one telsa,my name is alec
l .format::占位
例:
print(‘my name is %s my age is %s‘ %(‘egon‘,18))
print(‘my name is {} my age is {}‘.format(‘egon‘,18))
C:\python3\python.exe D:/python/untitled/two_day.py
my name is egon my age is 18
my name is egon my age is 18
l count说明
统计l在整个字符串出现的次数,可以按索引范围规定内统计
msg=‘hello word‘
print(msg.count(‘l‘,0,4))
print(msg.count(‘l‘,0,3))
C:\python3\python.exe D:/python/untitled/two_day.py
2.3 练习题
l 去除空格及打印以al开头的字符串
name = ‘ alex oldboy‘
#print(name.strip(‘ ‘))
name = ‘alex‘
a=name.startswith(‘al‘)
print(a)
C:\python3\python.exe D:/python/untitled/two_day.py
False
l 以l为分隔符
a=name.split(‘l‘)
print(a)
C:\python3\python.exe D:/python/untitled/two_day.py
[‘a‘, ‘ex‘]
l 将小写转化成大写
# print(name.upper())
#
# print(name.lower())
C:\python3\python.exe D:/python/untitled/two_day.py
ALEX
alex
l 输出name 变量对应的值的第2个字符
print(name[2])
print(name[1:3])
print(name[-2:])
C:\python3\python.exe D:/python/untitled/two_day.py
e
le
eX
l cente说明
msg=‘hello word‘
print(msg.center(30,‘=‘))
print(msg.rjust(30,‘=‘))
print(msg.ljust(30,‘=‘))
C:\python3\python.exe D:/python/untitled/two_day.py
==========hello word==========
====================hello word
hello word====================
2.4 打破顺序位置占位
语法:
print(‘my name is {x} my age is {y}‘.format(x=‘wxd‘,y=19))
print(‘{0} {0} {1}‘.format(‘egon‘,19))
执行:
C:\python3\python.exe D:/python/untitled/two_day.py
my name is wxd my age is 19
egon egon 19
Process finished with exit code 0
2.5 辨别find,rfind,index,rindex,ocunt
l find 说明
从左到右找,如有则返回第一个字符的索引;如果没有返回 -1
msg=‘hello word‘
print(msg.find(‘ell‘))
print(msg.find(‘x‘))
C:\python3\python.exe D:/python/untitled/two_day.py
1
-1
l index说明
从左到右找,有则返回第一个字符的索引;没有则报错
print(msg.index(‘d‘))
print(msg.index(‘x‘))
C:\python3\python.exe D:/python/untitled/two_day.py
9
Traceback (most recent call last):
File "D:/python/untitled/two_day.py", line 115, in <module>
print(msg.index(‘x‘))
ValueError: substring not found
2
1
2.6 判断数字
age=10
inp=input(‘>>: ‘).strip()
if inp.isdigit():
inp=int(inp)
if inp > age:
print(‘ok‘)
else:
print(‘you mast input number‘)
C:\python3\python.exe D:/python/untitled/two_day.py
>>: fd
you mast input number
第3章 列表类型
3.1 追加
my_frinds=[‘w‘,‘x‘,‘z‘,1,3,5]
my_frinds.append(‘6‘)
print(my_frinds)
#print(my_frinds)
3.2 删除
my_frinds=[‘w‘,‘x‘,‘z‘,1,3,5]my_frinds=[‘w‘,‘x‘,‘z‘,1,3,5]
my_frinds.append(‘6‘)
print(my_frinds)
#print(my_frinds)
‘‘‘‘‘
my_frinds=[‘w‘,‘x‘,‘z‘,1,3,5]
#del my_frinds[2] 按照所引来删除
print(my_frinds)
my_frinds.remove(‘x‘)
print(my_frinds)
C:\python3\python.exe D:/python/untitled/two_day.py
[‘w‘, ‘x‘, ‘z‘, 1, 3, 5]
[‘w‘, ‘z‘, 1, 3, 5]
3.3 remove与pop的区别
l remove 只是单纯的删除不会返回删除的值,并且是按照值来删除
l pop 按照索引去删除 默认从末尾开始删除,并且可以取出删除的值
第4章 列表其他操作
4.1 【重点】随意插入一个值
my_girl_frinds=[‘alex‘,‘wupei‘,‘yuanhao‘,4,5]
my_girl_frinds.insert(0,‘sb_alex‘)
print(my_girl_frinds)
C:\python3\python.exe D:/python/untitled/two_day.py
[‘sb_alex‘, ‘alex‘, ‘wupei‘, ‘yuanhao‘, 4, 5]
Process finished with exit code
4.2 追加加多个值
my_girl_frinds=[‘alex‘,‘wupei‘,‘yuanhao‘,4,5]
# my_girl_frinds.insert(0,‘sb_alex‘)
# print(my_girl_frinds)
my_girl_frinds.extend([1,2,34,5])
print(my_girl_frinds)
C:\python3\python.exe D:/python/untitled/two_day.py
[‘alex‘, ‘wupei‘, ‘yuanhao‘, 4, 5, 1, 2, 34, 5]
Process finished with exit code 0
4.3 【常用操作】统计
my_girl_frinds=[‘alex‘,‘wupei‘,‘yuanhao‘,4,5]
print(my_girl_frinds.count(‘alex‘))
C:\python3\python.exe D:/python/untitled/two_day.py
1
Process finished with exit code 0
4.4 练习题
4.4.1 先进先出
l1=[]
l1.append(‘first‘)
l1.append(‘second‘)
l1.append(‘third‘)
print(l1.pop(0))
print(l1.pop(0))
print(l1.pop(0))
C:\python3\python.exe D:/python/untitled/two_day.py
first
second
third
4.4.2 先进后出
l1=[]
l1.append(‘first‘)
l1.append(‘second‘)
l1.append(‘third‘)
print(l1.pop())
print(l1.pop())
print(l1.pop())
C:\python3\python.exe D:/python/untitled/two_day.py
third
second
first
第5章 元组
5.1 【重点】区别于列表
和列表的唯一区别是:元组是不可变的
ages=(10,20,18,33) #ages=tuble((10,12,18,33))
print(id(ages),type(ages),ages)
C:\python3\python.exe D:/python/untitled/two_day.py
41796456 <class ‘tuple‘> (10, 20, 18, 33)
5.2 【重点】按索引取值
ages=(10,20,18,33) #ages=tuble((10,12,18,33))
#print(id(ages),type(ages),ages)
print(ages.index(10))
C:\python3\python.exe D:/python/untitled/two_day.py
0
5.3 【重点】切片取值
ages=(10,20,18,33) #ages=tuble((10,12,18,33))
#print(id(ages),type(ages),ages)
print(ages[0])
C:\python3\python.exe D:/python/untitled/two_day.py
10
5.4 【重点】长度len
ages=(10,20,18,33) #ages=tuble((10,12,18,33))
#print(id(ages),type(ages),ages)
print(ages.__len__())
C:\python3\python.exe D:/python/untitled/two_day.py
4
5.5 成员运算in /not in
ages=(10,20,18,33) #ages=tuble((10,12,18,33))
#print(id(ages),type(ages),ages)
#print(ages.__len__())
print(19 not in ages)
C:\python3\python.exe D:/python/untitled/two_day.py
True
5.6 【重点】循环列表:
l=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]
index=0
while index < len(l):
print(l[index])
index+=1
C:\python3\python.exe D:/python/untitled/two_day.py
a
b
c
d
e
5.7 【重点】循环元组
msg_dic={
‘apple‘:10,
‘tesla‘:10000,
‘mac‘:300,
‘lenovo‘:3000,
‘chicken‘:10,
}
goods_l=[]
while True:
for key in msg_dic:
print(key,msg_dic[key])
choice = input(‘商品名称>>: ‘)
if choice not in msg_dic:continue
count = input(‘个数>>: ‘).strip()
if count.isdigit():
goods_l.append((choice,msg_dic[choice],int(count)))
print(goods_l)
lenovo 3000
商品名称>>: apple
个数>>: sdfsa
chicken 10
商品名称>>: apple
个数>>: 10
[(‘apple‘, 10, 19), (‘apple‘, 10, 10)]
apple 10
商品名称>>:
第6章 字典
l 字典作用:存多个值,key-value 存取,取值速度快
l 字典定义:key必须是不可变类型,value可以是任意类型
6.1 【重点】按key存取值:可存可取
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
print(info[(0,‘mac‘)])
C:\python3\python.exe D:/python/untitled/two_day.py
3000
6.2 【掌握】长度算法len
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
print(info[(0,‘mac‘)])
print(info.__len__())
C:\python3\python.exe D:/python/untitled/two_day.py
3000
4
6.3 【掌握】成员运算in /not in
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
print(info[(0,‘mac‘)])
print(info.__len__())
print(‘name‘ in info )
C:\python3\python.exe D:/python/untitled/two_day.py
3000
4
True
6.4 【重点】删除
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
print(info[(0,‘mac‘)])
print(info.__len__())
print(‘name‘ in info )
info.pop(‘name‘)
print(info)
C:\python3\python.exe D:/python/untitled/two_day.py
True
{‘age‘: 18, ‘sex‘: ‘male‘, (0, ‘mac‘): 3000}
6.5 【掌握】键keys()/值valuse()/键值对items()
6.6 注意:设计数据结构的根本目的是方便自己的存和取
列表取值如果没有直接报错
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
info.fromkeys()
print(info[‘name1‘])
C:\python3\python.exe D:/python/untitled/two_day.py
Traceback (most recent call last):
File "D:/python/untitled/two_day.py", line 186, in <module>
info.fromkeys()
TypeError: fromkeys expected at least 1 arguments, got 0
l get 取值不会报错可以赋值
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
print(info.get(‘name1‘,1))
C:\python3\python.exe D:/python/untitled/two_day.py
1
print(info.get(‘name1‘))
C:\python3\python.exe D:/python/untitled/two_day.py
None
6.7 两种赋值方式
6.7.1 链接式赋值
x=10
y=20
z=30
s=y=z
print(x,y,z)
m=10
n=20
m,n=n,m
print(m,n)
6.7.2 *—匹配赋值
从一个数据类型中解压出想要的值
t=(10.3,11.2,12.1,14.3,3.1)
x,y,z,a,b=t
print(x,y,z,a,b)
C:\python3\python.exe D:/python/untitled/two_day.py
10.3 11.2 12.1 14.3 3.1
t=(10.3,11.2,12.1,14.3,3.1)
x,*_,b=t
print(x,b)
C:\python3\python.exe D:/python/untitled/two_day.py
10.3 3.1
t=(10,20,30)
# x,y,z=t
# print(x,z)
x,*_=t
print(x)
6.8 for循环取值
直接取出字典的key和key值
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
for k,v in info.items():
print(k,v)
C:\python3\python.exe D:/python/untitled/two_day.py
name agen
age 18
sex male
(0, ‘mac‘) 3000
6.9 setdefault
有则不改,返回已经有的值,没有则新增,返回新增的值
6.9.1 传统添加多值
info={‘name‘:‘agen‘,‘age‘:18,‘sex‘:‘male‘,(0,‘mac‘):3000}
# for k,v in info.items():
# print(k,v)
if ‘hobbis‘ not in info:
info[‘hobbis‘]=[]
info[‘hobbis‘].append(‘music‘)
else:
info[‘hobbis‘].append(‘read‘)
if ‘hobbis‘ not in info:
info[‘hobbis‘]=[]
info[‘hobbis‘].append(‘music‘)
else:
info[‘hobbis‘].append(‘read‘)
print(info)
第一个if后的结果
C:\python3\python.exe D:/python/untitled/two_day.py
{‘name‘: ‘agen‘, ‘age‘: 18, ‘sex‘: ‘male‘, (0, ‘mac‘): 3000, ‘hobbis‘: [‘music‘]}
第二个if后的结果
C:\python3\python.exe D:/python/untitled/two_day.py
{‘name‘: ‘agen‘, ‘age‘: 18, ‘sex‘: ‘male‘, (0, ‘mac‘): 3000, ‘hobbis‘: [‘music‘, ‘read‘]}
Process finished with exit code 0
6.10 setdefault加值
如果存在key则不修改,如果不存在就添加
info.setdefault(‘hobbies‘,[]).append(‘music‘)
info.setdefault(‘hobbies‘,[]).append(‘read‘)
print(inf
C:\python3\python.exe D:/python/untitled/two_day.py
{‘name‘: ‘agen‘, ‘age‘: 18, ‘sex‘: ‘male‘, (0, ‘mac‘): 3000, ‘hobbies‘: [‘music‘, ‘read‘]}
Process finished with exit code 0
第7章 集合
7.1 特点:
l 每个元素必须是不可变类型(可hash,可作为字典的key)
l 没有重复的元素
l 无序
7.2 【重点】作用:去重
符号一览表
符号 |
定义 |
| |
合集 |
& |
交集 |
- |
差集 |
^ |
对称差集 |
== |
相同集合 |
>,>= ,<,<= |
父集,子集 |
练习:
pythons={‘alex‘,‘egon‘,‘yuanhao‘,‘wupeiqi‘,‘gangdan‘,‘biubiu‘}
linuxs={‘wupeiqi‘,‘oldboy‘,‘gangdan‘}
#求出即报名python又报名linux课程的学员名字集合
print(pythons & linuxs)
#求出所有报名的学生名字集合
print((pythons | linuxs))
print(len(pythons | linuxs))
#求出只报名python课程的学员名字
print(pythons - linuxs)
#求出没有同时这两门课程的学员名字集合
print(pythons ^linuxs)
C:\python3\python.exe D:/python/untitled/two_day.py
{‘wupeiqi‘, ‘gangdan‘}
{‘biubiu‘, ‘gangdan‘, ‘alex‘, ‘oldboy‘, ‘wupeiqi‘, ‘yuanhao‘, ‘egon‘}
7
{‘egon‘, ‘biubiu‘, ‘yuanhao‘, ‘alex‘}
{‘biubiu‘, ‘oldboy‘, ‘alex‘, ‘egon‘, ‘yuanhao‘}
7.3 常用操作
7.3.1 删除
sl={1,2,3,‘a‘,4}
print(sl.pop())
sl.remove(‘a‘)
sl.remove(‘as‘)
print(sl)
1
Traceback (most recent call last):
File "D:/python/untitled/two_day.py", line 233, in <module>
sl.remove(‘as‘)
KeyError: ‘as‘
注意:
l pop随机删除,并返回删除的结果
l remove 单纯的删除,不会返回结果,如果删除的元素不在则报错
7.3.2 交集判断isdisjoint
sl={1,2,3,‘a‘,4}
s2={4,5}
print(sl.isdisjoint(s2))
如果sl和s2没有交集则返回True
7.4 【掌握】关系运算
7.5 去重并定序
l=[‘a‘,‘b‘,1,‘a‘,‘a‘]
print(list(set(l)))
C:\python3\python.exe D:/python/untitled/two_day.py
[‘b‘, ‘a‘, 1]
7.6 循环
l=[‘a‘,‘b‘,1,‘a‘,‘a‘]
#print(list(set(l)))
l_new=list()
s=set()
for item in l:
if item not in s:
s.add(item)
l_new.append(item)
print(item)
C:\python3\python.exe D:/python/untitled/two_day.py
a
b
1
第8章 作业一: 三级菜单
要求:
l 打印省、市、县三级菜单
l 可返回上一级
l 可随时退出程序
8.1 方法一
#作业 三级菜单
‘‘‘
menu = {
‘beijing‘:{
‘haidian‘:{
‘wudaokou‘:{
‘soho‘:{},
‘wangyi‘:{},
‘google‘:{},
},
‘zhongguancun‘:{
‘aiqiyi‘:{},
‘qichezhijia‘:{},
‘youku‘:{},
},
‘shangdi‘:{
‘baidu‘:{},
},
},
‘changping‘:{
‘shahe‘:{
‘laonanhai‘:{},
‘beihang‘:{},
},
‘tiantongyuan‘:{},
‘huilongguan‘:{},
},
‘chaoyang‘:{},
‘dongcheng‘:{},
},
‘shanghai‘:{
‘minhang‘:{
‘renminguangchang‘:{
‘zhajidian‘:{}
}
},
‘zhabei‘{
‘huochezhan‘:{
‘xiiecheng‘:{}
},
},
‘pudong‘:{},
},
‘shandong‘:{},
}
exit_flag = False
current_layer = menu
layers = [menu]
while not exit_flag:
for k in current_layer:
print(k)
choice = input (">>:").strip()
if choice == "b":
current_layer =layers[-1]
layers.pop()
elif choice not in current_layer:continue
else:
layers.append(current_layer)
current_layer = current_layer[choice]
‘‘‘
方法二:
################################################
# Task Name: 三级菜单 #
# Description:打印省、市、县三级菜单 #
# 可返回上一级 #
# 可随时退出程序 #
#----------------------------------------------#
# Author:Wang_sir #
################################################
zone = {
‘山东‘ : {
‘青岛‘ : [‘四方‘,‘黄岛‘,‘崂山‘,‘李沧‘,‘城阳‘],
‘济南‘ : [‘历城‘,‘槐荫‘,‘高新‘,‘长青‘,‘章丘‘],
‘烟台‘ : [‘龙口‘,‘莱山‘,‘牟平‘,‘蓬莱‘,‘招远‘]
},
‘江苏‘ : {
‘苏州‘ : [‘沧浪‘,‘相城‘,‘平江‘,‘吴中‘,‘昆山‘],
‘南京‘ : [‘白下‘,‘秦淮‘,‘浦口‘,‘栖霞‘,‘江宁‘],
‘无锡‘ : [‘崇安‘,‘南长‘,‘北塘‘,‘锡山‘,‘江阴‘]
},
‘浙江‘ : {
‘杭州‘ : [‘西湖‘,‘江干‘,‘下城‘,‘上城‘,‘滨江‘],
‘宁波‘ : [‘海曙‘,‘江东‘,‘江北‘,‘镇海‘,‘余姚‘],
‘温州‘ : [‘鹿城‘,‘龙湾‘,‘乐清‘,‘瑞安‘,‘永嘉‘]
},
‘安徽‘ : {
‘合肥‘ : [‘蜀山‘,‘庐阳‘,‘包河‘,‘经开‘,‘新站‘],
‘芜湖‘ : [‘镜湖‘,‘鸠江‘,‘无为‘,‘三山‘,‘南陵‘],
‘蚌埠‘ : [‘蚌山‘,‘龙子湖‘,‘淮上‘,‘怀远‘,‘固镇‘]
},
‘广东‘ : {
‘深圳‘ : [‘罗湖‘,‘福田‘,‘南山‘,‘宝安‘,‘布吉‘],
‘广州‘ : [‘天河‘,‘珠海‘,‘越秀‘,‘白云‘,‘黄埔‘],
‘东莞‘ : [‘莞城‘,‘长安‘,‘虎门‘,‘万江‘,‘大朗‘]
}
}
province_list = list(zone.keys()) #省列表
# flag = False
# flag1 = False
while True:
print(" 省 ".center(50,‘*‘))
for i in province_list:
print(province_list.index(i)+1,i) #打印省列表
pro_id = input("请输入省编号,或输入q(quit)退出:") #省ID
if pro_id.isdigit():
pro_id = int(pro_id)
if pro_id > 0 and pro_id <= len(province_list):
pro_name = province_list[pro_id-1] #根据省ID获取省名称
city_list = list(zone[pro_name].keys()) #根据省名称获取对应的值,从新字典中获取key,即市列表
while True:
print(" 市 ".center(50,‘*‘))
for v in city_list:
print(city_list.index(v)+1,v) #打印市列表
city_id = input("请输入市编号,或输入b(back)返回上级菜单,或输入q(quit)退出:")
if city_id.isdigit():
city_id = int(city_id)
if city_id > 0 and city_id <= len(city_list):
city_name = city_list[city_id-1] #根据市ID获取市名称
town_list = zone[pro_name][city_name] #根据省名称获取对应的值,从新字典中获取值,即县列表
while True:
print(" 县 ".center(50,‘*‘))
for j in town_list:
print(town_list.index(j)+1,j)
back_or_quit = input("输入b(back)返回上级菜单,或输入q(quit)退出:")
if back_or_quit == ‘b‘:
break #终止此层while循环,跳转到上一层While。
elif back_or_quit == ‘q‘:
# flag1 = True
# break #根据标志位结束程序。
exit()
else:
print("输入非法!")
else:
print("编号%d不存在。"%city_id)
elif city_id == ‘b‘:
break
elif city_id == ‘q‘:
# flag = True
# break
exit()
else:
print("输入非法!")
# if flag1:
# break
else:
print("编号%d不存在。"%pro_id)
elif pro_id == ‘q‘:
break
else:
print("输入非法!")
# if flag or flag1:
# break
第9章 作业二:请闭眼写出购物车程序
需求:
l 用户名和密码存放于文件中,格式为:egon|egon123
l 启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
l 允许用户根据商品编号购买商品
l 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
l 可随时退出,退出时,打印已购买商品和余额
#写出购物车
# -*- coding: utf-8 -*-
product_list = [
["Iphone",5800],
["MAC PRO",16800],
["Bike",800],
["Coffee",30],
]
shopping_list = []
salary = input("请输入你的工资:")
#判断是否为数字
if salary.isdigit():
salary = int(salary)
while True:
for index,item in enumerate(product_list):
#打出菜单
print(index,item[0],item[1])
choice = input("请选择要购买的商品编号[quit]>>:")
if choice.isdigit():
choice = int(choice)
if choice >=0 and choice < len(product_list):
#判断钱是否够用
p = product_list[choice]
if p[1] <= salary:
shopping_list.append(p)
salary -= p[1]
print("Added \033[32;1m[%s]\033[0m into your shopping cart,and your current balance is \033[1;31;40m%s\033[0m"%(p,salary))
else:
print("钱不够,你只有 \033[5;31;42m[%s] \033[0m "% salary)
else:
print("没有此商品...")
elif choice == "quit":
print("已购买的商品".center(50,"-"))
for i in shopping_list:
print(i)
print("Your left balance is ",salary)
exit()
else:
print("未识别,请输入正确的指令!!")
以上是关于字符串列表元组字典参数的主要内容,如果未能解决你的问题,请参考以下文章