3.列表简介
3.1访问列表元素
print(bicycles[0])
添加、修改和删除元素
# 修改
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# 添加
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
# 插入
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
# 删除
# 1. 使用del语句删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
# 2. 使用方法pop()删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
-----------------------------
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
# 3. 弹出列表中任何位置处的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
# 4. 根据值删除元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
组织列表
# 使用方法 sort()对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
---------------
['audi', 'bmw', 'subaru', 'toyota']
# 使用函数 sorted()对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
---------------------------------------------
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
# 确定列表的长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
4.操作列表
# 遍历整个列表
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
# 使用函数 range()
for value in range(1,5):
print(value)
-------------------------
1
2
3
4
# 使用 range()创建数字列表
numbers = list(range(1,6)) #可指定步长
print(numbers)
# 对数字列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
0
max(digits)
9
sum(digits)
45
# 列表解析 将for循环和创建新元素的代码合并成一行
squares = [value**2 for value in range(1,11)]
---------------------------------------------
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
['charles', 'martina', 'michael']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
['charles', 'martina', 'michael', 'florence']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
['michael', 'florence', 'eli']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:]) # 此方法可输出末尾的任何切片 打印最后三位队员名字
# 遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
# 复制列表
friend_foods = my_foods[:]
5.元组
# 遍历元组中的所有值
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
# 修改元组变量 虽然不能修改元组的元素,但可以给存储元组的变量赋值
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
------------------------------
Original dimensions:
200
50
Modified dimensions:
400
100
6.字典
# 访问字典中的值
alien_0 = {'color': 'green'}
print(alien_0['color'])
# 添加键—值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
# 修改字典中的值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
# 删除键— 值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
6.3遍历字典
# 遍历所有的键— 值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
# 遍历字典中的所有键
for name in favorite_languages.keys():
print(name.title())
# 遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_
# languages.keys():替换为for name in favorite_languages:,输出将不变
# 按顺序遍历字典中的所有键
# 使用函数sorted()来获得按特定顺序排列的键列表的副本
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
# 遍历字典中的所有值
# 若要剔除重复项,可使用集合(set)。
# 集合类似于列表,但每个元素都必须是独一无二的:
for language in favorite_languages.values():
print(language.title())
for language in set(favorite_languages.values()):
print(language.title())
6.4嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中
可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典
# 字典列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
-------------------------------------
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
# 在字典中存储列表
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# 在字典中存储字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
7.while循环与列表和字典
# 在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# 删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
8.函数
使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。
这让Python依然能够正确地解读位置实参
# 让实参变成可选的
def get_formatted_name(first_name, last_name, middle_name=''):
# 传递列表
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
# 禁止函数修改列表
# 可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件
function_name(list_name[:]) # 切片表示法[:]创建列表的副本
# 传递任意数量的实参
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# 形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封
# 装到这个元组中
# 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
9.类
9.1创建和使用类
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " rolled over!")
# 根据类创建实例
my_dog = Dog('willie', 6)
# 访问属性 调用方法
my_dog.name
my_dog.sit()
my_dog.roll_over()
9.2使用类和实例
# 指定默认值
class Car():
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
my_new_car = Car('audi', 'a4', 2016)
# 修改属性的值
#1.直接通过实例进行修改;
my_new_car = Car('audi', 'a4', 2016)
my_new_car.odometer_reading = 23
#2.通过方法进行设置;
def update_odometer(self, mileage):
"""将里程表读数设置为指定的值"""
self.odometer_reading = mileage
my_new_car.update_odometer(23)
#3通过方法进行递增(增加特定的值)
def increment_odometer(self, miles):
"""将里程表读数增加指定的量"""
self.odometer_reading += miles
my_used_car.increment_odometer(100)
9.3继承
# 子类的方法__init__()
# 创建子类的实例时, Python首先需要完成的任务是给父类的所有属性赋值。为此,子类的方法__init__()需要父类施以援手
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
# super()是一个特殊函数,帮助Python将父类和子类关联起来。
# 这行代码让Python调用ElectricCar的父类的方法__init__(),让ElectricCar实例包含父类的所有属性。
# 父类也称为超类(superclass),名称super因此而得名
# Python 2.7 中的继承
class Car(object):
def __init__(self, make, model, year):
class ElectricCar(Car):
def __init__(self, make, model, year):
super(ElectricCar, self).__init__(make, model, year)
# 函数super()需要两个实参:子类名和对象self。为帮助Python将父类和子类关联起来,这些实参必不可少。
# 另外,在Python 2.7中使用继承时,务必在定义父类时在括号内指定object。
# 重写父类的方法
def ElectricCar(Car):
--snip--
def fill_gas_tank():
"""电动汽车没有油箱"""
print("This car doesn't need a gas tank!")
# Python将忽略 Car类中的方法fill_gas_tank(),转而运行上述代码。
# 使用继承时,可让子类保留从父类那里继承而来的精华,并剔除不需要的糟粕
# 将实例用作属性
# 不断给ElectricCar类添加细节时,我们可能会发现其中包含很多专门针对汽车电瓶的属性和方法。
# 在这种情况下,我们可将这些属性和方法提取出来,放到另一个名为Battery的类中,
# 并将一个Battery实例用作ElectricCar类的一个属性
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self, battery_size=70):
pass
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""
初始化父类的属性,再初始化电动汽车特有的属性
"""
super().__init__(make, model, year)
self.battery = Battery()
# 调用属性的方法
class Battery():
def get_range(self):
pass
my_tesla = ElectricCar('tesla', 'model s', 2016)
my_tesla.battery.get_range()
9.5.Python 标准库
# 字典让你能够将信息关联起来,但它们不记录你添加键—值对的顺序。
# 要创建字典并记录其中的键—值对的添加顺序,可使用模块collections中的OrderedDict类
# OrderedDict实例的行为几乎与字典相同,区别只在于记录了键—值对的添加顺序。
9.6.类编码风格
类名应采用驼峰命名法,即将类名中的每个单词的首字母都大写,而不使用下划线。实例名
和模块名都采用小写格式,并在单词之间加上下划线。
对于每个类,都应紧跟在类定义后面包含一个文档字符串。这种文档字符串简要地描述类的
功能,并遵循编写函数的文档字符串时采用的格式约定。每个模块也都应包含一个文档字符串,对其中的类可用于做什么进行描述
需要同时导入标准库中的模块和你编写的模块时,先编写导入标准库模块的import语句,再
添加一个空行,然后编写导入你自己编写的模块的import语句。在包含多条import语句的程序中,这种做法让人更容易明白程序使用的各个模块都来自何方。
10.文件和异常
10.1 从文件中读取数据
# 读取整个文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
# 函数open()返回一个表示文件的对象
# 关键字with在不再需要访问文件后将其关闭。
# 可在print语句中使用rstrip(),删除多余的空行
print(contents.rstrip())
# 在Windows系统中,在文件路径中使用反斜杠(\)而不是斜杠(/)
with open('text_files\filename.txt') as file_object:
# 创建一个包含文件各行内容的列表
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
# 读取文本文件时,Python将其中的所有文本都解读为字符串。
# 如果你读取的是数字,并要将其作为数值使用,
# 就必须使用函数int()将其转换为整数,或使用函数float()将其转换为浮点数。
10.2写入文件
# 写入空文件
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
# 打开文件时,可指定读取模式('r')、 写入模式('w')、
# 附加模式('a')或让你能够读取和写入文件的模式('r+')。
# 如果你省略了模式实参, Python将以默认的只读模式打开文件
# Python只能将字符串写入文本文件。
# 要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式
# 写入多行时,函数write()不会在你写入的文本末尾添加换行符
10.3 异常
# 使用 try-except 代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
# 使用异常避免崩溃
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
10.4存储数据
# 使用 json.dump()和 json.load()
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
11.测试代码
# 单元测试和测试用例
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""测试name_function.py"""
def test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗? """
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()
# 这个类必须继承unittest.TestCase类,这样Python才知道如何运行你编写的测试
# 我们运行test_name_function.py时,所有以test_打头的方法都将自动运行
11.2测试类
# unittest Module中的断言方法
assertEqual(a, b) #核实a == b
assertNotEqual(a, b) #核实a != b
assertTrue(x) #核实x为True
assertFalse(x) #核实x为False
assertIn(item, list) #核实item在list中
assertNotIn(item, list) #核实item不在list中