python学习笔记


二. 变量和简单数据类型

变量和简单的数据类型

命名只能包含字母、数字和下划线,不能以数字开头,不能包含空格

英文引号引起的都是字符串,三个引号可以创建跨行字符串

要在字符串中插入变量的值,可在前引号前加上字母f,再将要插入的变量放在花括号内

字符串

三.列表

列表简介

列表2

列表相关的常用方法

四.操作列表

操作列表

创建列表切片

元组的定义和遍历

五.if语句

条件测试

if语句

六.字典

字典

字典的常用方法

七.用户输入和while循环

用户输入

while循环

八.函数

函数

函数返回值

常用内置函数

1.导入整个模块
1
2
3
import module_name

moudule_name.function_name()

使用import语句导入模块,并通过模块名.函数名的语法,来使用其中的任意一个函数

2.导入特定的函数
1
2
from module_name import function_name
from module_name import function_0, function_1, function_2

此种语法调用函数时无须点号

3.使用as给函数指定别名
1
from module_name import function_name as fn
4..使用as给模块指定别名
1
import module_name as mn

九.类

类1

类2

根据约定,首字母大写的名称指的是类,小写的名称指的是根据类创建的实例,类中的函数称为方法

__ init _ _函数,此函数开头和末尾各有两个下划线

self形参:指向实例本身的引用,实例的每次调用都会自动传入自身,这样使得实例能够访问类中的属性和方法

1
2
3
4
5
6
7
8
9
10
class Dog:
...

my_dog = Dog('Willie', 6)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")

my_dog.sit()
my_dog.roll_over()

接着可以通过点号语法,来访问实例的属性

执行调用时,Python 首先会找到 my_dog 实例,随后通过在类中使用 self.nameself.age 来引用与这个实例相关联的属性,以获取名字和年龄

与访问属性类似,同样使用点号语法来调用实例的方法,从而让实例“动起来”

Python 会在类中查找调用的方法,然后运行方法体中的语句

十.文件和异常

文件和异常

pathlib模块:帮助我们在各种操作系统中处理文件和目录

splitlines方法:获得把文本按行分割所得的列表

异常

序列化

json.dumps( )进行存储,json.loads( )进行读取

十五.生成数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]

plt.style.use('seaborn') 使用内置样式
fig, ax = plt.subplots() subplot()可在一张图片中绘制一个或多个图表,fig表示整张图
ax.plot(input_values, squares, linewidth=3)

# Set chart title and label axes. 标题及坐标轴
ax.set_title("Square Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Square of Value", fontsize=14)

# Set size of tick labels. 刻度标记大小
ax.tick_params(axis='both', labelsize=14)

plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt

x_values = range(1, 1001)
y_values = [x**2 for x in x_values]

plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10) 绘制点scatter() 参数c设置颜色 s设置点大小
颜色映射 c设置成y值列表 cmap选择映射颜色
# Set chart title and label axes.
ax.set_title("Square Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Square of Value", fontsize=14)

# Set size of tick labels.
ax.tick_params(axis='both', which='major', labelsize=14)

# Set the range for each axis.
ax.axis([0, 1100, 0, 1100000])

plt.show()

随机漫步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from random import choice

class RandomWalk:
"""A class to generate random walks."""

def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
self.num_points = num_points

# All walks start at (0, 0).
self.x_values = [0]
self.y_values = [0]

def fill_walk(self):
"""Calculate all the points in the walk."""

# Keep taking steps until the walk reaches the desired length.
while len(self.x_values) < self.num_points:

# Decide which direction to go and how far to go in that direction.
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance

y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance

# Reject moves that go nowhere.
if x_step == 0 and y_step == 0:
continue

# Calculate the new position.
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step

self.x_values.append(x)
self.y_values.append(y)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import matplotlib.pyplot as plt

from random_walk import RandomWalk

# Keep making new walks, as long as the program is active.
while True:
# Make a random walk.
rw = RandomWalk(50_000)
rw.fill_walk()

# Plot the points in the walk.
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(15, 9)) 指定生成的图形尺寸
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,
edgecolors='none', s=1)
删除点的黑色轮廓
# Emphasize the first and last points.绘制起点和终点
ax.scatter(0, 0, c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',
s=100)

# Remove the axes.隐藏坐标轴
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

plt.show()

keep_running = input("Make another walk? (y/n): ")
if keep_running == 'n':
break

掷骰子

1
2
3
4
5
6
7
8
9
10
11
12
13
from random import randint

class Die:
"""A class representing a single die."""

def __init__(self, num_sides=6):
"""Assume a six-sided die."""
self.num_sides = num_sides

def roll(self):
""""Return a random value between 1 and number of sides."""
return randint(1, self.num_sides)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from plotly.graph_objs import Bar, Layout
from plotly import offline

from die import Die

# Create two D6 dice.
die_1 = Die()
die_2 = Die()

# Make some rolls, and store results in a list.
results = []
for roll_num in range(1000):
result = die_1.roll() + die_2.roll()
results.append(result)

# Analyze the results. 计算每个点出现的次数
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result+1):
frequency = results.count(value)
frequencies.append(frequency)

# Visualize the results.
x_values = list(range(2, max_result+1)) list转换成列表
data = [Bar(x=x_values, y=frequencies)] bar()表示用于绘制条形图的数据集

x_axis_config = {'title': 'Result', 'dtick': 1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling two D6 dice 1000 times',
xaxis=x_axis_config, yaxis=y_axis_config) 布局对象
offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6.html')

十六.下载数据

CSV文件:数据作为一系列以逗号分隔的值写入的文件


文章作者: RickyLove
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 RickyLove !
  目录