Python
列表
#列表
bycicle = ["1","2","3"]
print(bycicle)
print(bycicle[0])
print(bycicle[-1]) #下标为-1即为最后一列.空列表会返回索引错误
#修改列名
bycicle[0] = "0"
print(bycicle)
#元素添加到列表末尾
bycicle.append("4")
print(bycicle)
#在固定位置添加元素
bycicle.insert(0,"0")
print(bycicle)
#删除元素
del bycicle[0]
print(bycicle)
# 删除末尾元素
bycicle.pop()
print(bycicle)
# 删除列表的值,若有就删除,没有则不变
bycicle.remove("3")
print(bycicle)
#列表
cars = ["benz","bmw","audi","toyota"]
# 升序排列,没有修改列表的值
print(sorted(cars))
print(cars) #由此可见
# 升序排列,修改列表的值
cars.sort()
print(cars)
# 逆序排列,已经修改了列表的顺序
cars.sort(reverse = True)
print(cars)
#列表长度
print(len(cars))
#列表
cars = ["benz","bmw","audi","toyota"]
#注意冒号
for car in cars :
print(car + "is in this list")
#前闭后开原则
for i in range(1,4):
print(i)
number = list(range(1, 4))
print(number) #[1, 2, 3]
#步长为 2
number = list(range(1, 10, 2))
print(number) #[1, 3, 5, 7, 9]
#列表
square = [value**2 for value in range(1,10)]
print(square)
print(square[0:6]) #等价于print(square[ :6])
print(square[2: ]) #输出第3个元素直到末尾
print(square[-5: ]) #负数返回离列表末尾相应的元素
print(min(square))
print(max(square))
print(sum(square))
元组
#元组
dimension = (200,50)
print(dimension[0])
for i in dimension:
print(i)
'''
dimension[0] = 1
TypeError: 'tuple' object does not support item assignment
'''
#可以重新定义元组
dimension = (400,1000)
print(dimension)
'''
#元组
available_topping = ['mushrooms', 'olives', 'green peppers', 'vegatables']
requeset_topping = ['mushrooms', 'frensh fries', 'vegatables']
for request in requeset_topping:
if request in available_topping:
print(request + " is in this list")
else:
print(request + " isn't in this list")
字典
#字典
alien = {'color': 'green','point': 5}
print(alien)
# 直接添加键值对
alien['x_position'] = 15;
alien['y_position'] = 20;
print(alien)
#永久删除point键值对
del alien['point']
print(alien)
#字典
user = {
'username' : 'lhw',
'age': "22",
'school': 'zzu'
}
for key, value in user.items():
print("\nKey: " + key );
print("Value: " + value);
for key in user.keys():
print(key)
for value in user.values():
print(value)
#字典
people_language = {
'Mike' : 'C',
'jen' : 'python',
'john' : 'java',
'phil' : 'python'
}
# set不显示重复项
for language in set(people_language.values()):
print(language)
#字典&&列表,外星人例子
aliens = []
for i in range(30):
new_alien = {'color': 'green','speed' : 'medium', 'points' : 5}
aliens.append(new_alien)
print("length = " + str(len((aliens))))
for alien in aliens[0:3]:
alien['color'] = 'yellow'
alien['points'] = 10
for alien in aliens[0:5]:
print(alien)
# pizza例子,存储节点披萨的信息
pizza = {
'crust' : 'thick',
'toppings': ['mishrooms','extra cheese']
}
print(pizza)
print("pizza's crust is :" + pizza['crust'])
print("pizza's toppings are: ")
for topping in pizza['toppings'] :
print("\t " + topping)
# 字典中单个字段对应多个值,需要注意加中括号[]
people_language = {
'Mike' :['c','java'] ,
'jen' : ['python','solidity'],
'john' : ['java','javascript'],
'phil' : ['python']
}
for name,languanges in people_language.items():
print(name)
for languange in languanges :
print(languange)
print("\n")
如果将'phil' : ['python'],改为 ‘phil' : 'python',运行结果下图所示
更复杂的字典:
6-11 城市:创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城
市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'hangzhou' : {
'country' : 'China',
'population' : 1000000,
'fact' : 'xihu'
},
'NewYork': {
'country': 'US',
'population': 10000000,
'fact': 'qian'
},
'London': {
'country': 'England',
'population': 10000000,
'fact': 'yingguo'
}
}
for name, info in cities.items():
print("城市名字是:" + name)
for key in info.keys():
print(key + " : " + str(info[key]))
class
定义
class Restaurant():
"""A class representing a restaurant."""
def __init__(self, name, cuisine_type):
"""Initialize the restaurant."""
self.name = name.title()
self.cuisine_type = cuisine_type
self.number = 0
def describe_restaurant(self):
"""Display a summary of the restaurant."""
msg = self.name + " serves wonderful " + self.cuisine_type + "."
print("\n" + msg)
def open_restaurant(self):
"""Display a message that the restaurant is open."""
msg = self.name + " is open. Come on in!"
print("\n" + msg)
def set_number(self, _number):
self.number = _number
print("人数是:" + str(self.number))
def update_number(self, _number):
self.number += _number
print("人数是:" + str(self.number))
restaurant = Restaurant('the mean queen', 'pizza')
restaurant.set_number(100)
restaurant.update_number(100)
# print(restaurant.name)
# print(restaurant.cuisine_type)
#
# restaurant.describe_restaurant()
# restaurant.open_restaurant()
继承和重载
class User():
"""Represent a simple user profile."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
self.login_attempts = 0
def describe_user(self):
"""Display a summary of the user's information."""
print("\n" + self.first_name + " " + self.last_name)
print(" Username: " + self.username)
print(" Email: " + self.email)
print(" Location: " + self.location)
def greet_user(self):
"""Display a personalized greeting to the user."""
print("\nWelcome back, " + self.username + "!")
def increment_login_attempts(self):
"""Increment the value of login_attempts."""
self.login_attempts += 1
def reset_login_attempts(self):
"""Reset login_attempts to 0."""
self.login_attempts = 0
# eric = User('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska')
# eric.describe_user()
# eric.greet_user()
#
# print("\nMaking 3 login attempts...")
# eric.increment_login_attempts()
# eric.increment_login_attempts()
# eric.increment_login_attempts()
# print(" Login attempts: " + str(eric.login_attempts))
#
# print("Resetting login attempts...")
# eric.reset_login_attempts()
# print(" Login attempts: " + str(eric.login_attempts))
class Admin(User):
def __init__(self,first_name, last_name, username, email, location):
super().__init__(first_name, last_name, username, email, location)
self.privileges = []
def show_privileges(self):
print("privileges: " + str(self.privileges))
admin = Admin('1','2','3','4','5')
admin.privileges = ["121",'12121','1212']
admin.show_privileges()
导入类
导入部分类
from module_name import class_0, class_1 ...
导入整个模块
import module_name
# 使用方式为
module_name.class_name()
导入模块所有类
from module_name import *
python标准库
有序字典
有序字典和无序字典比较:https://www.cnblogs.com/gide/p/6370082.html
from collection import OrderedDict
随机数
from random import randint
class Die():
def __init__(self,sides = 6):
self.sides = sides
def roll_die(self):
print("色子数是:" + str(randint(1,self.sides)))
die1 = Die()
die1.roll_die()
die2 = Die(10)
die2.roll_die()
die3 = Die(20)
die3.roll_die()
文件
- 读 ’r’
- 写 ‘w’
- 附加 ‘a’
- 读写 ’r+’
读文件
with open("pi.txt") as pi:
contents = pi.read()
print(contents)
# 消除空格,加上rstrip()
文件路径
# Windows下是反斜杠\
# Linux和OS X下是斜杠/
'text_files / file_name,txt'
逐行读取
file_name = "pi.txt"
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip())
创建一个包含文件各行内容的列表
file_name = "pi.txt"
with open(file_name) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
使用文件中的内容
'''逐行读取'''
file_name = "pi.txt"
with open(file_name) as file_object:
lines = file_object.readlines()
string = ''
for line in lines:
string += line
print(string)
三种读取方式
file_name = "pi.txt"
list = []
with open(file_name) as file_object:
contents = file_object.read()
print(contents)
with open(file_name) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
list.append(line.rstrip())
print(list)
写文件
file_name = "pi.txt"
with open(file_name,'a') as file_object:
file_object.write(" append")
with open(file_name,'r') as file_object:
contents = file_object.read()
print(contents)
写入多行记得使用换行符
异常处理
'''处理文件无法找到异常'''
file_name = "pi.txt"
while True:
name = input("请输入您的姓名:")
try:
with open(file_name,'a') as file_object:
file_object.write(str(name) + "\n")
except FileNotFoundError:
print("文件" + file_name + "无法找到")
else:
print("你好, " + name)
'''统计单词数目'''
def count_words(file_name):
try:
with open(file_name,'r') as file_object:
contents = file_object.read()
except FileNotFoundError:
#pass语句什么也不做
pass
else:
# 计算文件包含多少个单词,通过空格分割
words = contents.split()
return (len(words))
print(count_words('pi.txt'))
'''加法计算器'''
def add(para1, para2):
try:
sum = int(para1) + int(para2)
except ValueError:
print("值类型错误")
else:
print("和是:" + str(sum))
while True:
para1 = input('加数')
para2 = input('加数')
add(para1,para2)
读取GBK编码异常:
UnicodeDecodeError: 'gbk' codec can't decode byte 0x9d in position 1160
解决方式如下:在open函数添加编码格式
# 统计字符串出现次数
file_path2 = 'The Adventures of Tom Sawyer by Mark Twain.txt'
try:
with open(file_path2,'r',encoding='UTF-8') as file_object2:
content_dog = file_object2.read()
except FileNotFoundError:
pass
else:
print("'dog'出现次数:\n" + str(content_dog.lower().count('the')))
JSON
JSON文件中至少是
[]
json.dump()
import json
numbers = ['1','2',3,423,232]
with open('txt\\dog.txt','a') as file_object:
json.dump(numbers,file_object)
json.load()
import json
with open('json\\number.json') as file_object:
string = json.load(file_object)
print(string)
文件内容为 "qd"