文章目录
列表
修改、添加和删除
motorcycles = ['honda', 'yamaha', 'suzuki']
#1. 修改元素
motorcycles[0] = 'ducati'
#2. 添加元素
# 末尾插入
motorcycles.append('xiaodi')
# 指定位置插入
motorcycles.insert(0, 'xiaodi')
#3. 删除元素
del motorcycles[0]
#删除最后位置
motorcycles.pop()
# 删除指定位置
motorcycles.pop(0)
# 根据名称匹配删除
motorcycles.remove('xiaodi')
排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
#1. 字母顺序排序
cars.sort()
#2. 字母反向排序
cars.sort(reverse=True)
#3. sort排序是永久性的,sorted排序为临时的,不影响原列表
cars.sorted()
#4. 反转列表元素的排列顺序
cars.reverse()
#5. 列表的长度
len(cars)
列表元素的访问
cars = ['bmw', 'audi', 'toyota', 'subaru']
#1. 类似C/C++的数组方式访问
cars[0]
#2. 访问最后一个元素
cars[-1]
遍历列表
#1. for循环遍历
cars = ['bmw', 'audi', 'toyota', 'subaru']
for car in cars:
print(car)
#2. 切片
#提取第0~2个元素
print(cars[0:3]) #['bmw', 'audi', 'toyata']
#提取第0~2个元素
print(cars[:3]) #['bmw', 'audi', 'toyata']
#提取第2~最后一个元素
print(cars[2:]) #['toyota', 'subaru']
#提取最后三个元素
print(cars[-3:]) #['audi', 'toyota', 'subaru']
数值列表
创建数值列表
#1. 使用函数range()
for value in range(1, 5): #生成1, 2,3,4
print(value)
#2. 使用range()创建数字列表
numbers = list(range(1,6)) #[1, 2, 3, 4, 5]
#3. range()可指定步长,打印1~10内的偶数
even_numbers = list(range(2,11,2))
print(even_numbers) #[2, 4, 6, 8, 10]
#4. 将for循环和创建新列表的代码合成一行
numbers = [value**2 for value in range(1, 11)] #numbers[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
数值列表的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
#1. 找出列表的最大值,最小值,总和
max(digits), min(digits), sum(digits)
复制列表
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
my_digits = digits[:] #my_digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
元组
元组的基本操作和列表一致,元组使用()表示digits = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
字典
在python中字典是一些列键-值对,每个键都与一个值相关联,可以使用键来访问与之相关联的值,与键相关联的值可以是数字,字符串,列表乃至字典,可将任何python对象用作字典中的值。
添加字典中键-值对
alien_0 = {'color':'green', 'points':5}
#添加键-值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25 #alien_0 = {'color':'green', 'points':5, 'x_position':0, 'y_position':25}
修改字典中键-值对
alien_0 = {'color':'green'}
#修改键-值对
alien_0['color'] = 'yellow'
删除字典中键-值对
alien_0 = {'color':'green', 'points':5}
del alien_0['points'] #alien_0 = {'color':'green'}
字典的遍历
#1. 遍历字典中的所有键值对
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
'3thd':'fermi',
'4th':'enrico',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
#2. 遍历字典中所有的键值
for key in user_0.keys():
print(key)
#3. 按顺序遍历字典中的所有键值
for key in sorted(user_0.keys()):
print(key)
#4. 遍历字典中的所有的值
for value in user_0.values():
print(value)
#5. 遍历字典中的所有的值,去掉重复项,可使用集合(set),集合类似于列表,但每个元素必须是独一无二的
for value in set(user_0.values()):
print(value)
嵌套
列表中存储字典
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)
字典中使用列表
favorite_languages = {
'jen':['python', 'ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are: ")
for language in languages:
print("\t" + language.title())
字典中存储字典
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()
函数
定义函数
#使用关键字def来告诉python要定义一个函数
def greet_user():
"""显示简单的问候语"""
print("Hello!")
greet_user() #调用函数
向函数传递参数
def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user("jesse")
传递实参
#1. 位置实参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\n I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
#2. 关键字实参
describe_pet(animal_type='hamster', pet_name='harry')
#3. 默认值
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("\n I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
返回值
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + " " + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(misician)
传递列表
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
禁止函数修改列表
funciton_name(list_name[:])
传递任意数量的实参
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
使用任意数量的关键字实参
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
user_profile = build_profile('albert', 'einstein',
location = 'princeton',
field = 'physics')
print(user_profile)
类
创建和使用类
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!")
继承
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
文件和异常
读取文件
读取整个文件
with open('file.txt') as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip()) #删除多出来的空行
逐行读取
with open('file.txt') as file_object:
for line in file_object:
print(line)
创建一个包含文件各行内容的列表
with open('file.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
写入文件
写入空文件
with open('file.txt', 'w') as file_object:
file_object.write("I love programming.")
写入多行
#注意:写入字符串末尾的"\n",会出现字符串写成一行
with open('file.txt', 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
附加到文件
# open函数的参数使用'a'
with open('file.txt', 'a') as file_object:
file_object.write("I also love finding meaning in large datasets. \n");
异常
使用try-except代码块
#实例1
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
#实例2
filename = 'file.txt'
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " dose not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about" + str(num_words) + " words.")
#实例3
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
--snip--
except FileNotFoundError:
pass
else:
--snip--
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt']
for filename in filenames:
count_words(filename)
测试代码
测试函数
def get_formated_name(first, last):
"""Generate a neatly formatted full name."""
full_name = first + ' ' + last
return full_name.title()
from name_function import get_formated_name
print("Enter 'q' at any time to quit.")
while True:
first = input("\n Please give me a first name: ")
if first == 'q':
break
last = input("Please give me a last name: ")
if last == 'q':
break
formatted_name = get_formated_name(first, last)
print("\nNeatly formatted name: " + formatted_name + '.')
import unittest
from name_funtion import get_formated_name
# NameTestCase类,用于包含一系列针对get_formated_name()的单元测试,
#这个类必须继承unittest.TestCase类,这样Python才知道如何运行你编写的测试
class NameTestCase(unittest.TestCase):
"""测试name_function.py"""
def test_first_last_name(self):
"""能够正确的处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formated_name('jains', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
def test_first_last_middle_name(self):
"""能够正确的处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
formatted_name = get_formated_name(
'wolfgang', 'mozart', 'amadeus')
self.assertEqual(formatted_name, "Wolfgang Amadeus Mozart')
unittest.main()
测试类
各种断言方法
方法 | 用途 |
---|---|
assertEqual(a,b) | 核实 a == b |
assertNotEqual(a, b) | 核实 a != b |
assertTrue(x) | 核实x为True |
assertFalse(x) | 核实x为Flase |
assertIn(item, list) | 核实item在list中 |
assertNotIn(item, list) | 核实item不在list中 |
一个要测试的类
class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self, question)
"""创建一个空列表,用于存储答案"""
self.question = []
def show_question(self):
"""显示调查问卷"""
print(question)
def store_response(self, new_response):
"""存储单份调查答案"""
self.responses.append(new_response)
def show_results(self):
"""显示收集到的所有答卷"""
print("Survey results:")
for response in responses:
print('- ' + response)
from survey import AnonymousSurvey
#定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
#显示问题并存储答案
my_survey.show_question()
print("Enter 'q' at any time to quit. \n")
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_response(response)
#显示调查结果
print("\n Thank you to everyone who participated in the survey!")
my_survey.show_results()
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试单个答案会被妥善的存储"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
unittest.main()
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
"""
unittest.TestCase包含setUp(),只需要创建这些对象一次,并在每个测试方法中都可使用他们。
方法setUp()做了两件事情:创建一个调查对象self.my_survey,创建一个答案列表self.responses
"""
def setUp(self):
"""创建一个调查对象和一组答案,供使用的测试方法使用"""
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_rsponse(self):
"""测试单个答案会被妥善的存储"""
for response in self.responses:
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey_responses)
def test_store_three_responses(self):
"""测试三个答案会被妥善的存储"""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.rsponses:
self.assertIn(response, self.my_survey.responses)
unittest.main()