python函数控制列表和词典_【Python第二篇】Python基础之列表、字典、集合、函数...

本节内容

列表、元组操作

字符串操作

字典操作

集合操作

函数

三元运算

lambda表达式

内置函数(文件操作)

函数递归

1. 列表、元组操作

列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

定义列表

通过下标访问列表中的元素,下标从0开始计数

切片:取多个元素

>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]>>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4

['Tenglan', 'Eric', 'Rain']>>> names[1:-1] #取下标1至-1的值,不包括-1

['Tenglan', 'Eric', 'Rain', 'Tom']>>> names[0:3]

['Alex', 'Tenglan', 'Eric']>>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样

['Alex', 'Tenglan', 'Eric']>>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写

['Rain', 'Tom', 'Amy']>>> names[3:-1] #这样-1就不会被包含了

['Rain', 'Tom']>>> names[0::2] #后面的2是代表,每隔一个元素,就取一个

['Alex', 'Eric', 'Tom']>>> names[::2] #和上句效果一样

['Alex', 'Eric', 'Tom']

View Code

追加

>>>names

['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy']>>> names.append("我是新来的")>>>names

['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']

View Code

插入

>>>names

['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']>>> names.insert(2,"强行从Eric前面插入")>>>names

['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']>>> names.insert(5,"从eric后面插入试试新姿势")>>>names

['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']

View Code

修改

>>>names

['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']>>> names[2] = "该换人了"

>>>names

['Alex', 'Tenglan', '该换人了', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']

View Code

删除

>>> del names[2]>>>names

['Alex', 'Tenglan', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']>>> del names[4]>>>names

['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']>>>

>>> names.remove("Eric") #删除指定元素

>>>names

['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新来的']>>> names.pop() #删除列表最后一个值

'我是新来的'

>>>names

['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']

View Code

扩展

>>>names

['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']>>> b = [1,2,3]>>>names.extend(b)>>>names

['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]

View Code

统计

>>>names

['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]>>> names.count("Amy")2

View Code

排序&翻转

>>>names

['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]>>> names.sort() #排序

Traceback (most recent call last):

File"", line 1, in TypeError: unorderable types: int()< str() #3.0里不同数据类型不能放在一起排序了,擦

>>> names[-3] = '1'

>>> names[-2] = '2'

>>> names[-1] = '3'

>>>names

['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3']>>>names.sort()>>>names

['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']>>> names.reverse() #反转

>>>names

['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']

View Code

获取下标

>>>names

['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']>>> names.index("Amy")2 #只返回找到的第一个下标

View Code

元组

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法

它只有2个方法,一个是count,一个是index。

程序练习

请写出以下程序。

程序:购物车程序

需求:

启动程序后,让用户输入工资,然后打印商品列表

允许用户根据商品编号购买商品

用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

可随时退出,退出时,打印已购买商品和余额

程序代码如下:

salary = input('input your salary:')ifsalary.isdigit():

salary=int(salary)else:

exit('Invalid data type')

welcome_msg= 'Welcome to WuMei shopping mall'.center(50,'-')print(welcome_msg)

exit_flag=False

product_list=[

('Iphone',5888),

('Mac Air',8000),

('Mac Pro',9000),

('XiaoMi2',19.9),

('Coffee',30),

('Tesla',820000),

('Bike',700),

('Cloth', 200),]

shop_cat=[]while exit_flag is notTrue:print('product list'.center(50,'-'))for name in enumerate(product_list): #枚举元组

index =name[0]

p_name= name[1][0]

p_price= name[1][1]print(index,'.',p_name,p_price)

user_choice= input("[q=quit,c=check]What do you want to buy?:")ifuser_choice.isdigit():

user_choice=int(user_choice)if user_choice

p_item=product_list[user_choice]if p_item[1] <=salary:

shop_cat.append(p_item)

salary-= p_item[1]print("Add [%s] into shop car ,you blance is \033[31;1m[%s]\033[0m" %(p_item,salary))else:print('Your blance is [%s],cannot afford this.'%salary)else:print('\033[31;1m Invalid option,please select 0-%d\033[0m' %(len(product_list)-1) )else:if user_choice == 'q' or user_choice =='quit':print("purchased products as blow".center(40,'-'))for name inshop_cat:print(name)print('END'.center(40,'-'))print('Your balance is [%s]'%salary)print('bye')

exit_flag=Trueelif user_choice == 'c' or user_choice =='check':print("purchased products as blow".center(40,'-'))for name inshop_cat:print(name)print('END'.center(40,'-'))print('Your balance is \033[31;1m[%s]\033[0m'% salary)

View Code

2. 字符串操作

name = "chris,jack,rain"

print(name.split(","))print("|".join(name))

username= input('your name:')if username.strip() == 'fuyf':print('weblcome')

name= 'fu ye feng'

print(name.center(40,'-'))print('' inname)print(name.capitalize())

msg= "hello,{name},it's been a long {age} no see"

print(msg.format(name='fuyf',age=22))

msg2= "hahah{0},dddd{1}"

print(msg2.format('chris',22))

age= input('your age:')ifage.isdigit():

age=int(age)else:print("invalid data type")

name= 'fuyf123'

print(name.endswith('f'))print(name.startswith('3'))print(name.upper().lower())

format :>>> msg = "my name is {}, and age is {}"

>>> msg.format("alex",22)'my name is alex, and age is 22'

>>> msg = "my name is {1}, and age is {0}"

>>> msg.format("alex",22)'my name is 22, and age is alex'

>>> msg = "my name is {name}, and age is {age}"

>>> msg.format(age=22,name="ale")'my name is ale, and age is 22'format_map>>> msg.format_map({'name':'alex','age':22})'my name is alex, and age is 22'

View Code

3. 字典操作

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

语法:

info = {

'stu1101': "TengLan Wu",

'stu1102': "LongZe Luola",

'stu1103': "XiaoZe Maliya",

}

字典的特性:

dict是无序的

key必须是唯一的,so 天生去重

字典常用操作:

增加>>> info["stu1104"] = "苍井空"

>>>info

{'stu1102': 'LongZe Luola', 'stu1104': '苍井空', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}

修改>>> info['stu1101'] = "武藤兰"

>>>info

{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}

删除>>>info

{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}>>> info.pop("stu1101") #标准删除姿势

'武藤兰'

>>>info

{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}>>> del info['stu1103'] #换个姿势删除

>>>info

{'stu1102': 'LongZe Luola'}>>>

>>>

>>>

>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}>>>info

{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除

>>>info.popitem()

('stu1102', 'LongZe Luola')>>>info

{'stu1103': 'XiaoZe Maliya'}

查找>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}>>>

>>> "stu1102" in info #标准用法

True>>> info.get("stu1102") #获取

'LongZe Luola'

>>> info["stu1102"] #同上,但是看下面

'LongZe Luola'

>>> info["stu1105"] #如果一个key不存在,就报错,get不会,不存在只返回None

Traceback (most recent call last):

File"", line 1, in KeyError:'stu1105'多级字典嵌套及操作

av_catalog={"欧美":{"www.youporn.com": ["很多免费的,世界最大的","质量一般"],"www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],"letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],"x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]

},"日韩":{"tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]

},"大陆":{"1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]

}

}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"

print(av_catalog["大陆"]["1024"])#ouput

['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

其它姿势#values

>>>info.values()

dict_values(['LongZe Luola', 'XiaoZe Maliya'])#keys

>>>info.keys()

dict_keys(['stu1102', 'stu1103'])#setdefault

>>> info.setdefault("stu1106","Alex")'Alex'

>>>info

{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}>>> info.setdefault("stu1102","龙泽萝拉")'LongZe Luola'

>>>info

{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}#update

>>>info

{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}>>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}>>>info.update(b)>>>info

{'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}#items

info.items()

dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])#通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个

>>> dict.fromkeys([1,2,3],'testd')

{1: 'testd', 2: 'testd', 3: 'testd'}

View Code

循环dict

#方法1

for key in info:

print(key,info[key])

#方法2

for k,v in info.items(): #会先把dict转成list,数据里大时莫用

print(k,v)

程序练习

程序: 三级菜单

要求:

打印省、市、县三级菜单

可返回上一级

可随时退出程序

menu ={'湖南':{'长沙':['望城县','刘阳市','开元区',

],'株洲': ['荷塘区','醴陵市','攸县',

]

},'浙江':{'杭州':['滨江区','西湖区','江干区',

]

}

}

exit_flag=False

current_layer=menu

layers=[menu]while notexit_flag:for k incurrent_layer:print(k)

choice= input("选择菜单>>:").strip()if choice == "b" or choice =='back': #返回上一级菜单

current_layer = layers[-1]

layers.pop()elif choice not incurrent_layer:print('\033[31;1myour select menu invalid,please select again:\033[0m')continue

else:

layers.append(current_layer)

current_layer= current_layer[choice]

4.集合操作

集合是一个无序、不重复的数据组合,它的主要作用如下:

去重,把一个列表变成集合,就自动去重了

关系测试,测试两组数据之前的交集、差集、并集等关系

#创建集合

s = set([3, 5, 9, 3,10])

s1= {1,'ff'}

s2= set("Hello")

s1= {1,2,3}

s2= {2,3,4}

s1.add(44) #加入一条数据

print(s1)

s1.clear()#清空数据

s3 = s1.difference(s2) #s1中有,s2没有的

s3= s1.symmetric_difference(s2) #s1中有,s2没有的和s2中有,s1没有的

s1.difference_update(s2) #s1中有的,s2中没有的更新为s1

s1.symmetric_difference_update(s2)

s1.discard(2) #删除某个元素

s2.remove(2) #删除某个元素,不存在则报错

s2.pop()#随机移除

ret= s2.pop() #记录随机删除的数

print(ret)

s3=s1.intersection(s2) #取交集

s1.intersection_update(s2)#交集更新到s1

s1.issubset(s2) #子集

s1.issuperset(s2) #超集

s3 = s1.union(s2) #并集

li= [11,22,33]

s1.update(li)#加入多条数据,可以是列表、元组、字符串等可以迭代的对象

print(s1)

5.函数

函数式编程最重要的是增强代码的重用性和可读性

定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可

特性:

减少重复代码

使程序变的可扩展

使程序变得易维护

语法定义:

def 函数名(参数):

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值