Python有五个标准的数据类型
- Numbers(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Dictionary(字典)
万丈高楼平地起,这五个标准的数据类型讲贯穿于整个Python
Python支持四种不同的数字类型:
- int(有符号整型)
- long(长整型[也可以代表八进制和十六进制])
- float(浮点型)
- complex(复数)
python的字串列表有2种取值顺序:
- 从左到右索引默认0开始的,最大范围是字符串长度少1
- 从右到左索引默认-1开始的,最大范围是字符串开头
List(列表) 是 Python 中使用最频繁的数据类型。
- 列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(即嵌套)。
- 列表用 [ ] 标识,是 python 最通用的复合数据类型。
- 列表中值的切割也可以用到变量 [头下标:尾下标] ,就可以截取相应的列表,从左到右索引默认 0 开始,从右到左索引默认 -1 开始,下标可以为空表示取到头或尾。
- 加号 + 是列表连接运算符,星号 * 是重复操作。
元组是另一个数据类型,类似于List(列表)。
- 元组用”()”标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。
字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。
- 列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
- 字典用”{ }”标识。字典由索引(key)和它对应的值value组成。
Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言。Python基础知识包含Python数据类型,数据结构,控制流等,与其他高级语言类似,顺序语句、条件语句、循环语句等是其基本结构。
1.Python基本命令
1.1 列出已安装的包
pip list
1.2 查看可升级的包
pip list -o
1.3 安装包
pip install SomePackage # 最新版本pip install SomePackage==1.5.0 # 指定版本
1.4 镜像站安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
1.5 升级包
pip install --upgrade SomePackage # 升级至最新版本pip install --upgrade SomePackage==1.5.0 # 升级为指定版本
1.6 卸载包
pip uninstall SomePackage
#导入sys库只是为了确认一下Python的版本
import sys #导入pandas
import pandas as pdimport numpyimport matplotlib
print('Python 版本为:' + sys.version)
print('Pandas 版本为:' + pd.__version__)
print('Numpy 版本为:' + pd.__version__)
print('Matplotlib 版本为:' + matplotlib.__version__)
2.变量与保留字
2.1 变量
变量相当于一个内存容器,可以指定存入不同的数据类型,可以是整数,小数或字符。
#Jupyter notebook打印多个变量结果
from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity='all'
使用如上的代码可以使得变量结果多行显示。
name = "大话数据分析" # 字符串
age = 18 # 赋值整型变量
height = 178.4 # 浮点型
name
age
height
2.2 保留字
Python中的保留字不能用作变量名称,常见的Python保留字如下所示。
import keyword
print(keyword.kwlist)
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘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’]
3. 三大数据类型
3.1 str
3.1.1 初识字符串
# 字符串定义
a = 'hello world'
a
‘hello world’
type(a) #类型
len(a) #长度
str
Out[82]:11
3.1.2 索引和切片
使用[头下标:尾下标]来切片,其中下标是从 0 开始算起,切片的范围前闭后开,表示方括号的左边可以切切到,而右边切不到。
# 切片索引
a[0:5],a[:5]
(‘hello’, ‘hello’)
a[:],a[::1]
(‘hello world’, ‘hello world’)
#负号代表从右边开始截取,这里表示取反a[::-1]
‘dlrow olleh’
3.1.3 方法
'-'.join(a)
a.replace('world','boy')
a.zfill(15)#返回指定长度的字符串,原字符串右对齐,前面填充0
today=['2015','10','15']
print("-".join(today))
‘h-e-l-l-o- -w-o-r-l-d’
Out[6]:’hello boy’
Out[6]:’0000hello world’
2015-10-15
a.count('o') #字符串计数
a.index('o') #字符串索引
a.find('o') #字符串查找
a.capitalize()#首字母大写
a.title() #设置为标题
a.upper() #字母大写
a.lower() #字母小写
a.startswith('h') #开头包含的字符
2
Out[70]:4
Out[70]:4
Out[70]:’Hello world’
Out[70]:’Hello World’
Out[70]:’HELLO WORLD’
Out[70]:’hello world’
Out[70]:True
s = '**2021/12/16**'
s.strip('*')#去除头和尾部字符
s.lstrip('*')#去除左边字符
s.rstrip('*')#去除右边字符
s.strip('*').split('/') #去除头和尾部字符,并按照/分隔开
‘2021/12/16’
‘2021/12/16**’
‘**2021/12/16’
[‘2021′, ’12’, ’16’]
3.1.4 字符运算
# 运算符运算:+ 和 *
s = '大话数据分析'
'Hello' + ' ' + s
s * 3
‘Hello 大话数据分析’
‘大话数据分析大话数据分析大话数据分析’
3.2 int
num = 10
print(type(num))#基本的算术运算
print('加法:',num + 2)
print('减法:',num - 2)
print('乘法:',num * 2)
print('除法',num / 2)
print('地板除法',num // 2)
print('幂运算',num ** 2)
print('余数',num % 2)
加法: 12
减法: 8
乘法: 20
除法 5.0
地板除法 5
幂运算 100
余数 0
#算术运算的顺序,先计算括号里边的内容,再乘除后加减
print(num * (2 + 1))
30
#数字自增长
num = 10
num = num + 1
print(num)#或者+=方式
num = 10
num += 1
print(num)#数字自乘积
num = 10
num = num * 5
print(num)
#使用*=
num = 10
num *= 5
print(num)
11
11
50
50
3.3 float
num = 10.01
print(type(num))
<class ‘float’>
#基本的算术运算
print('加法:',num + 2)
print('减法:',num - 2)
print('乘法:',num * 2)
print('除法',num / 2)
print('地板除法',num // 2)
print('幂运算',num ** 2)
print('余数',num % 2)
加法: 12.01
减法: 8.01
乘法: 20.02
除法 5.005
地板除法 5.0
幂运算 100.20009999999999
余数 0.009999999999999787
#算术运算的顺序,先计算括号里边的内容,再乘除后加减
print(num * (2 + 1))
30.03
#数字自增长
num = 10.0
num = num + 1
rint(num)
#或者+=方式
num = 10.0
num += 1
print(num)
#数字自乘积
num = 10.0
num = num * 5
print(num)
#或者*=
num = 10.0
num *= 5
print(num)
11.0
11.0
50.0
50.0
3.4 类型转化
str,int,float数据类型相互转化。
#将string内容为数字,字符串相连
num1 = '10'
num2 = '20'
num3 = '30.0'
print('字符串相连:',num1+num2+num3)
#使用int()函数将字符型转换为int,float函数将字符型转换为float
num1_int = int(num1)
num2_int = int(num2)
num3_int = int(float(num3))
print('数值相加:',num1_int + num2_int + num3_int)
字符串相连:102030.0
数值相加:60
4. 三大数据结构
4.1 列表
4.1.1 初识列表
列表是 Python 中使用最频繁的数据类型,列表中的每个元素都可变的,可以对每个元素进行修改和删除,且列表是有序的,每个元素的位置是确定的,可以用索引去访问每个元素,并且,列表中的元素可以是Python中的任何对象,比如字符串、整数、元组、也可以是list等Python中的对象。
# 列表定义
lst = [1,2,3,4,5,6,7,8,9]
lst
[1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = list(range(5))
lst
[0, 1, 2, 3, 4]
# 类型和长度
type(lst)
len(lst)
4.1.2 索引和切片
使用[头下标:尾下标]来截取部分字符串,其中下标是从 0 开始算起,可以是正数或负数,下标可以为空表示取到头或尾。
# 索引
lst = [1,2,3,4,5,6,7,8,9]
lst[0]
lst[-1]
9
# 切片
lst[0:4]
lst[:4]
lst[0:4:1]
lst[:]
lst[::-1]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[4, 3, 2, 1, 0]
lst[::1] #缺省为1,默认间隔一个位置提取
lst[::2] #步长为 2(间隔一个位置)来截取
[0, 1, 2, 3, 4]
[0, 2, 4]
4.1.3 方法
# append,列表末尾添加新的对象
lst = [0,1,2,3,4]
lst.append(5)
lst
[0, 1, 2, 3, 4, 5]
#extend合并列表内容
lst = [0,1,2,3,4]
lst.extend([5])
lst
[0, 1, 2, 3, 4, 5]
#insert指定位置插入数据
lst = [0,1,2,3,4]
lst.insert(1,5)
lst
[0, 5, 1, 2, 3, 4]
lst = [0,1,2,3,4]
lst.copy()
[0, 1, 2, 3, 4]
# remove
lst = [0,1,2,3,4]
lst.remove(4)
lst
[0, 1, 2, 3]
# count,index
lst = [7,8,5,4,3,3,5,6,7,5]
lst.count(5)
lst.index(3)
3
4
# 默认升序排列
lst = [7,8,5,4,3,3,5,6,7,5]
lst.sort()
lst
[3, 3, 4, 5, 5, 5, 6, 7, 7, 8]
4.1.4 列表运算
# 运算符运算:+ 和 *
lst = [1,2,3,4]
lst + [3,4,5]
lst * 2
[1, 2, 3, 4, 3, 4, 5]
[1, 2, 3, 4, 1, 2, 3, 4]
4.2 元组
元组可理解为一个固定列表,一旦初始化其中的元素便不可修改,只能对元素进行查询。
4.2.1 初识元组
# 元组的定义
t = (0, 1, 2, 3, 4)
t
(0, 1, 2, 3, 4)
t = tuple(range(5))
t
(0, 1, 2, 3, 4)
# 属性和长度
type(t)
len(t)
tuple
Out[8]:5
4.2.2 索引和切片
# 索引
t = (0, 1, 2, 3, 4)
t[0]
t[1]
t[-1]
0
1
4
# 切片
t = (0, 1, 2, 3, 4)
t[0:4]
t[:4]
t[0:4:1]
(0, 1, 2, 3)
Out[10]:(0, 1, 2, 3)
Out[10]:(0, 1, 2, 3)
t = (0, 1, 2, 3, 4)
t[:]
t[::-1]
(0, 1, 2, 3, 4)
Out[14]:(4, 3, 2, 1, 0)
t = (0, 1, 2, 3, 4)
t[::1]
t[::2]
(0, 1, 2, 3, 4)
Out[13]:(0, 2, 4)
# count---index
t = (2, 1, 2, 4, 2)
t.count(2)
t.index(2)
t.index(4)
3
Out[16]:0
Out[16]:3
4.2.3 元组运算
# 运算符运算:+ 和 *
t = (1, 2, 3, 4)
t + (4,5,6)
t * 2
(1, 2, 3, 4, 4, 5, 6)
Out[17]:(1, 2, 3, 4, 1, 2, 3, 4)
4.3 字典
字典中的数据必须以键值对的形式出现,其中,键是唯一的,不可重复,值可重复,字典中键(key)是不可变的,为不可变对象,不能进行修改;而值(value)是可以修改的,可以是任何对象。
4.3.1 初识字典
# 字典的定义: 键值对
d = {'a':10,'b':20,'c':30}
d
{‘a’: 10, ‘b’: 20, ‘c’: 30}
# 属性和长度
d = {'a':10,'b':20,'c':30}
type(d)
len(d)
4.3.2 索引和切片
# 索引
d = {'a':10,'b':20,'c':30}
d['b']
20
4.3.3 方法
# keys---values---items
d = {'a':10,'b':20,'c':30}
d.keys()
d.values()
d.items()
dict_keys([‘a’, ‘b’, ‘c’])
Out[24]:dict_values([10, 20, 30])
Out[24]:dict_items([(‘a’, 10), (‘b’, 20), (‘c’, 30)])
# update
d = {'a':10,'b':20,'c':30}
d.update({'d':40})
d
# pop
d = {'a':10,'b':20,'c':30}
d.pop('a')
# get
d = {'a':10,'b':20,'c':30}
d.get('b')
5. 三大控制流
5.1 if语句
当 if “判断条件” 成立时,则执行后面的语句,else 为可选语句,当条件不成立时可以执行该语句。
#if...else语句 缩进很重要
score = 60
if score < 60:
print('不及格') print('还需要在努力!')
else: print('很棒!及格了')
很棒!及格了
#if...elif语句
score = 75
if score <60: print('不及格') print('还需要在努力!')
elif score <70: print('成绩:{}'.format('及格'))
elif score <80: print('成绩:{}'.format('中等'))
elif score <90: print('成绩:{}'.format('良好'))
elif score <100: print('成绩:{}'.format('优秀'))
成绩:中等
5.2 while语句
在某特定条件下,循环执行某命令。
#whilea = 0
i = 100
while i < 100:
a=a+i
i=i+1
print(a)
5050
5.3 while……else……语句
else中的语句会在循环正常执行完(即不是通过break跳出而中断的)的情况下执行。
#while…else…
a = 1
b = 1
while a > b:
print(a)
else: print('数值大小相等')
数值大小相等
#while…if…else…
a = 1
b = 1
while a > b:
print(a)
if a < b:
print(b)
else: print('数值大小相等')
数值大小相等
#break 语句,跳出当前循环,结束语句
a = 10
b = 50
while a < b:
print(b)
a += 10
a = 10
b = 50
while a < b:
print(b)
a += 10
break
5.4 for 循环语句
对集合(如列表或元组)或迭代器进行迭代。
range函数用于产生一组间隔相等的整数序列的可迭代对象,可以指定起始值、终止值以及步长,常用于按索引对序列进行迭代。
a=0
for i in range(1,101):
a = a+i
print(a)
5050
#for
for i in range(1,5):
print(i * 10)
10
20
30
40
#for…if…else…
for i in range(1,5):
if i < 3: print(str(i) + 'Python')
else: print(str(i) + 'Java')
1Python
2Python
3Java
4Java
for i in range(1,5):
print(i)
if i > 2:
break
1
2
3
5.5循环控制语句
- break:结束(终止)循环
- continue:中止当前循环,跳到下一次循环的开始
- while true/break:实现一个永远不会自己停止的循环
- else:在使用break时,可以使用else语句在没有调用break时执行对应的语句
- pass:不做任何事情,一般用做占位语句
for a in 'This is Python!':
if a == ' ': pass
print('passed!')
break print(a)
– END –