一、操作列表
1、列表的创建和遍历
需要对列表中的每个元素都执行相同的操作时,可使用python中的for循环。
# 我是大青呐学习python笔记
#遍历列表
vegetables = ['tomato', 'potato', 'broccoli']
for vegetable in vegetables:
print(vegetable)
#创建数值列表
#range(a,b,c)从指定的第一个数字a开始达到指定的第二个数字b后停止,不包括第二个数字b,c为可选参数,指定步长。
for value in range(0, 5):
print(value)
for value in range(0, 10, 2):
print(value)
#使用list()函数可将range()结果直接转换为列表
numbers = list(range(0, 5))
print(numbers)
#可使用min()、max()、sum()等函数简单的处理数字列表
min(numbers)
max(numbers)
sum(numbers)
运行结果
tomato
potato
broccoli
0
1
2
3
4
0
2
4
6
8
[0, 1, 2, 3, 4]
2、列表切片
处理列表的部分元素——python称之为切片。
vegetables = ['tomato', 'potato', 'broccoli', 'cucumber']
print(vegetables[1:4]) # 打印该列表的一个切片,从第1个元素开始,到索引4前面的元素停止。
print(vegetables[:3]) # 如果没有制定第一个索引,python将自动从列表的开头开始
print(vegetables[0:]) # 如果没有制定末尾索引,Python将自动提取到列表末尾
#遍历切片
for vegetable in vegetables[:3]: #遍历前三种
print(vegetable)
运行结果
['potato', 'broccoli', 'cucumber']
['tomato', 'potato', 'broccoli']
['tomato', 'potato', 'broccoli', 'cucumber']
tomato
potato
broccoli
二、字典
Python内置了字典:dict的支持,dict全称dictionary,在Python中,字典是一系列键-值对,每个键都与一个值相关联。
shop = {'vegetable': 'potato', 'price': '5.2'}
#访问字典
print(shop['vegetable'])
print(shop['price'])
#添加键-值对
shop['number'] = 10
shop['weight'] = 3
print(shop)
#删除键-值对
del shop['number']
print(shop)
#由类似对象组成的字典
favorite_vagetables = {
'John': 'tomato',
'Jen': 'potato',
'Susan': 'cucumber',
}
print("Jen's favorite vegetable is "+favorite_vagetables['Jen'])
#遍历字典
for name,vegetable in favorite_vagetables.items():
print(name.title()+"'s favorite vagetable is "+vegetable.title()+".")
#遍历字典中的所有键,使用keys()
for name in favorite_vagetables.keys():
print(name.title())
运行结果
potato
5.2
{'vegetable': 'potato', 'price': '5.2', 'number': 10, 'weight': 3}
{'vegetable': 'potato', 'price': '5.2', 'weight': 3}
Jen's favorite vegetable is potato
John's favorite vagetable is Tomato.
Jen's favorite vagetable is Potato.
Susan's favorite vagetable is Cucumber.
John
Jen
Susan
在字典操作中,可使用函数sorted()来获得按特定顺序排列的键列表的副本;values()方法可返回一个值列表;set()方法可提取出列表中独一无二的元素。