了解一下带有示例的python的简单介绍

发布时间:2022-11-16

本文目录一览:

  1. python中的类型转换都有什么,用在什么场景下?
  2. 【Python基础】python基本语法规则有哪些?
  3. 进来吧,给自己10分钟,这篇文章带你直接学会python
  4. Python基本语法都有哪些?
  5. Python模拟随机游走图形效果示例
  6. [建议收藏!10 种 Python 聚类算法完整操作示例](#建议收藏!10 种 Python 聚类算法完整操作示例)

python中的类型转换都有什么,用在什么场景下?

1. 字符串(string)

  • 示例:'余庆','yuqing','123','Hello!'
  • 特点:用引号括起来的文本。
  • 转换方式:使用 str() 函数将数据转换为字符串类型。

2. 整数(int)

  • 示例:-1, 0, 1, 2, 123
  • 特点:不带小数点和引号的普通数字。
  • 转换方式:使用 int() 函数转换,只有符合整数规范的字符串类数据才能被转换。

注意

  • 整数形式的字符串如 '6''1' 可以被转换。
  • 文字形式(如中文、火星文)或标点符号不能被转换。
  • 小数形式的字符串不能使用 int() 函数转换。
  • int() 函数会直接抹零,输出整数部分。

3. 浮点数(float)

  • 示例:-0.33,3.1415926,1.0
  • 特点:带小数点的数字,运算结果会存在误差。
  • 转换方式:使用 float() 函数转换,可以将整数和字符串转换为浮点类型,但字符串必须是数字形式。

【Python基础】python基本语法规则有哪些?

Python基本语法

Python的语法相对比C、C++、Java更加简洁,比较符合人的正常思维。本篇介绍Python的基本语法,通过本篇文章你可以学到以下内容:

  • 掌握Python的基本语法
  • 识别Python中的关键字

Python的特点

  • 面向对象:类
  • 语法块:使用缩进进行标记
  • 注释
    • 单行注释:#
    • 多行注释:"""'''
  • 打印与输出print(), input()
  • 变量:变量在赋值时确定类型
  • 模块:通过 import 模块名 加载模块

Python的标识符

  • 标识符用于给变量、常量、函数、语句块等命名。
  • 命名规则
    • 开头以字母或下划线 _ 开始。
    • 剩下的字符可以是字母、数字或下划线。
    • Python遵循小驼峰命名法。
    • 不可以使用Python中的关键字。

示例:

num = 10  # 这是一个int类型变量

错误命名示例:

  • 123rate(数字开头)
  • mac book pro(含有空格)
  • class(关键字)

Python关键字

以下列表中的关键字不可以当作标识符使用。Python语言的关键字只包含小写字母。

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

进来吧,给自己10分钟,这篇文章带你直接学会python

Python的语言特性

  • 强类型:变量类型是强制要求的。
  • 动态性:变量类型在运行时确定。
  • 隐式类型:不需要做变量声明。
  • 大小写敏感varVAR 代表不同的变量。
  • 面向对象:一切皆为对象。

获取帮助

你可以通过Python解释器获取帮助:

  • help(object):查看对象的帮助信息。
  • dir():显示对象的所有方法。
  • object.__doc__:显示对象的文档。

语法

  • Python中没有强制的语句终止字符。
  • 代码块通过缩进来指示。
  • 单行注释以 # 开头,多行注释以多行字符串的形式出现。
  • 赋值通过 = 实现,相等判断使用 ==
  • +=-= 用于增加/减少运算。

数据类型

Python有三种基本的数据结构:

  • 列表(list):类似一维数组。
  • 元组(tuple):不可变的一维数组。
  • 字典(dictionary):具有关联关系的数组(哈希表)。

字符串

  • 使用单引号 ' 或双引号 " 标示。
  • 多行字符串使用三个连续的单引号 ''' 或双引号 """
  • 使用 % 运算符填充字符串。

流程控制

  • 使用 if, for, while 实现流程控制。
  • for 用于枚举列表中的元素。
  • range(number) 用于生成数字列表。

函数

  • 使用 def 声明函数。
  • 可选参数可以设置默认值。
  • 函数可以返回元组。
  • Lambda函数是由一个单独的语句组成的特殊函数。

  • Python支持有限的多继承。
  • 私有变量和方法通过添加前导下划线 _ 声明。

导入

  • 使用 import [libname] 导入模块。
  • 使用 from [libname] import [funcname] 导入特定函数。

Python基本语法都有哪些?

1. 关于编码

  • 默认情况下,Python 3 源码文件以 UTF-8 编码。
  • 可以指定不同的编码方式:
# -*- coding: cp-1252 -*-

2. 标识符

  • 第一个字符必须是字母或下划线。
  • 其他字符可以是字母、数字或下划线。
  • 对大小写敏感。
  • Python 3 中支持中文变量名。

3. 保留字(关键字)

  • 关键字不能作为标识符使用。
  • 可以使用 keyword 模块查看所有关键字:
import keyword
keyword.kwlist

输出:

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

4. 注释

  • 单行注释以 # 开头。
  • 多行注释使用 '''"""

5. 缩进与多行语句

  • 使用缩进表示代码块。
  • 同一代码块的缩进必须一致。
  • 多行语句使用 \ 或在 [], {}, () 中自动换行。

6. 数字(Number)类型

  • int:整数,如 1
  • bool:布尔值,如 True
  • float:浮点数,如 1.23
  • complex:复数,如 1 + 2j

7. 字符串

  • 单引号和双引号使用完全相同。
  • 使用三引号 '''""" 表示多行字符串。
  • 使用 \ 转义字符。
  • 使用 r"" 表示原始字符串。
  • 字符串可以用 + 连接,用 * 重复。
  • 字符串索引从 0 开始,也可以使用负数索引。
  • 字符串不可变。
  • 字符串截取语法:变量[头下标:尾下标:步长]

示例:

str = 'Runoob'
print(str)  # 输出字符串
print(str[0:-1])  # 输出第一个到倒数第二个的所有字符
print(str[0])  # 输出第一个字符
print(str[2:5])  # 输出从第三个到第五个字符
print(str[2:])  # 输出从第三个开始后的所有字符
print(str * 2)  # 输出字符串两次
print(str + '你好')  # 连接字符串
print('hello\nrunoob')  # 使用反斜杠转义
print(r'hello\nrunoob')  # 原始字符串

8. 空行

  • 函数之间或类的方法之间用空行分隔。
  • 空行不是语法的一部分,但有助于代码维护。

9. 等待用户输入 input

input("\n\n按下 enter 键后退出。")

10. 同一行显示多条语句

使用分号 ; 分隔:

import sys; x = 'runoob'; sys.stdout.write(x + '\n')

11. 代码组

  • 缩进相同的一组语句构成一个代码块。
  • 复合语句如 if, while, def, class 以冒号 : 结束。

12. Print输出

  • 默认换行,不换行使用 end=""
x = "a"
y = "b"
print(x)
print(y)
print(x, end=" ")
print(y, end=" ")

13. import 与 from...import

  • 导入整个模块:import somemodule
  • 导入特定函数:from somemodule import somefunction
  • 导入多个函数:from somemodule import firstfunc, secondfunc
  • 导入所有函数:from somemodule import *

示例:

import sys
print('命令行参数为:')
for i in sys.argv:
    print(i)
print('\n python 路径为', sys.path)
from sys import argv, path
print('path:', path)

14. 命令行参数

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...

15. 一个有用的函数:help()

help(max)
print(max.__doc__)

Python模拟随机游走图形效果示例

简介

在Python中,可以利用数组操作来模拟随机游走。

示例代码

纯Python方式

import matplotlib.pyplot as plt
import random
position = 0
walk = [position]
steps = 200
for i in range(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)
fig = plt.figure()
plt.title("")
ax = fig.add_subplot(111)
ax.plot(walk)
plt.show()

NumPy方式

import matplotlib.pyplot as plt
import numpy as np
nsteps = 200
draws = np.random.randint(0, 2, size=nsteps)
steps = np.where(draws == 0, 1, -1)
walk = steps.cumsum()
fig = plt.figure()
plt.title("")
ax = fig.add_subplot(111)
ax.plot(walk)
plt.show()

多个随机游走

nwalks = 5
nsteps = 200
draws = np.random.randint(0, 2, size=(nwalks, nsteps))
steps = np.where(draws == 0, 1, -1)
walks = steps.cumsum(1)
fig = plt.figure()
plt.title("")
ax = fig.add_subplot(111)
for i in range(nwalks):
    ax.plot(walks[i])
plt.show()

建议收藏!10 种 Python 聚类算法完整操作示例

简介

聚类分析是无监督学习任务,用于发现数据中的自然分组。有许多聚类算法可供选择,没有单一的最佳算法。本节介绍10种流行的聚类算法及其完整操作示例。

1. 亲和力传播(Affinity Propagation)

from sklearn.cluster import AffinityPropagation
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, random_state=42)
model = AffinityPropagation(damping=0.5)
yhat = model.fit_predict(X)
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

2. 聚合聚类(Agglomerative Clustering)

from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=2)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

3. BIRCH

from sklearn.cluster import Birch
model = Birch(threshold=0.01, n_clusters=2)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

4. DBSCAN

from sklearn.cluster import DBSCAN
model = DBSCAN(eps=0.3, min_samples=10)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

5. K均值(K-Means)

from sklearn.cluster import KMeans
model = KMeans(n_clusters=2)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

6. Mini-Batch K-Means

from sklearn.cluster import MiniBatchKMeans
model = MiniBatchKMeans(n_clusters=2)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

7. 均值漂移(Mean Shift)

from sklearn.cluster import MeanShift
model = MeanShift()
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

8. OPTICS

from sklearn.cluster import OPTICS
model = OPTICS(eps=0.8, min_samples=10)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

9. 光谱聚类(Spectral Clustering)

from sklearn.cluster import SpectralClustering
model = SpectralClustering(n_clusters=2)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()

10. 高斯混合模型(Gaussian Mixture Model)

from sklearn.mixture import GaussianMixture
model = GaussianMixture(n_components=2)
yhat = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=yhat)
plt.show()