跳转至

基本数据类型

一、数值

1. 数值类型

python数值类型

  1. 整数
  2. 浮点数
  3. 复数
  4. 小数
  5. 分数
  6. 集合
  7. 布尔值 TrueFalse
  8. 内置函数和模块:round、math、random

2. 数值运算

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
>>> print(2+3)  # 加法
5
>>> print(8-3)  # 减法
5
>>> print(2*3)  # 乘法
6
>>> print(5/3)  # 真除
1.6666666666666667
>>> print(5//3)  # 向下取整除法,截除掉余数
1
>>> print(5**2)  # 幂运算
25
>>> print(5%2)  # 取余
1

3. 进制

3.1 进制表示

1
2
3
4
5
6
>>> 0b11111111  # 二进制
255
>>> 0o377       # 八进制
255
>>> 0xFF        # 十六进制
255

3.2 进制转换

1
2
3
4
5
6
>>> bin(255)    # 十进制转二进制
'0b11111111'
>>> oct(255)    # 十进制转八进制
'0o377'
>>> hex(255)    # 十进制转十六进制
'0xff'

4. 小数

1
2
3
# 在Windows平台Python 3.6.8中计算的结果,浮点数的结果并不精确
>>> print(0.1+0.1+0.1-0,3)
0.30000000000000004 3

如果要精确计算小数,需要使用小数对象

1
2
3
4
5
6
>>> from decimal import Decimal
>>> print(Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3'))
0.0
# 注意*:要在小数上加引号,否则输出的结果是下面的值
# >>> print(Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3))
# 2.775557561565156540423631668E-17

5. 分数

1
2
3
4
>>> from fractions import Fraction
>>> x = Fraction(6,8)
>>> print(x)
3/4

6. 整数浮点数装换

1
2
3
4
>>> int(3.14)
3
>>> float(3)
3.0

二、Python字符串

字符串就是一系列字符,在Python中,用引号括起来的都是字符串,引号可以是单引号('string')也可以是双引号("string")

1. 字符串的特点

  1. 字符串是单个字符的字符串序列,是有序的
  2. 不可变性,不可以对原始的字符串进行改变。

2. 字符串操作

2.1 索引

字符串的第一个字符下标为0。

1
string = "Life is short, You need Python"
  • 正索引
1
2
3
In [1]: string = "Life is short, You need Python"
In [2]: string[2]
Out[2]: 'f'
  • 负索引
1
2
3
In [1]: string = "Life is short, You need Python"
In [2]: string[-6]
Out[2]: 'P'

2.2 切片

切片的格式: string[start,end]

1
2
3
4
In [1]: string = "Life is short, You need Python"
# 范围是[5,7)不包含索引为7的字符
In [2]: string[5:7]
Out[3]: 'is'

当第一个索引值缺省时,从0开始。

1
2
3
4
In [1]: string = "Life is short, You need Python"

In [6]: string[:7]
Out[6]: 'Life is'

切片加步长

1
2
3
4
In [1]: s = '1234567890'

In [2]: s[2:8:2]
Out[2]: '357'

2.3 拼接

1
2
3
4
>>> s1 = 'hello '
>>> s2 = 'world'
>>> s1 + s2
'hello world'

2.4 重复

1
2
>>> print("hello"*5)
hellohellohellohellohello

2.5 长度

1
2
>>> len('hello')
5

3. 字符串方法

3.1 字符串大小写转换

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
>>> # 字符串首字符大写
... print("hello world".capitalize())
Hello world
>>> # 大小写翻转
... print("hello WORLD".swapcase())
HELLO world
>>> # 将字符串变为标题
... print("hello WORLD".title())
Hello World
>>> # 将字符串转为大写
... print("hello world".upper())
HELLO WORLD
>>> # 把字符串转为小写
... print("HELLO WORLD".lower())
hello world
>>> # 翻转字符串中的大小写
... print("hello WORLD".swapcase())
HELLO world

3.2 字符串分割

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
>>> # 以某个元素为分割点,将字符串分为3部分,从左往右找到的第一个元素为分割点
... print('helloworld'.partition('o'))
('hell', 'o', 'world')
>>> # 以某个元素为分割点,将字符串分为3部分,从右往左找到的第一个元素为分割点
... print('helloworld'.rpartition('o'))
('hellow', 'o', 'rld')
>>> # 替换原字符串中的元素,默认全部替换,可以指定替换几个(从左往右数)
... print("hello world".replace('o', 'a', 1))
hella world
>>> # 以某个元素为分割点,将字符串分割,从左往右分割n次
... print("hello world".split('o', 1))
['hell', ' world']
>>> # 以某个元素为分割点,将字符串分割,从右往左分割n次
... print("hello world".rsplit('o', 1))
['hello w', 'rld']
>>> # 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
... print('hello\nworld'.splitlines(True))
['hello\n', 'world']

3.3 字符串查找

1
2
3
4
5
6
7
8
9
>>> # 统计某个字符串从索引n到y出现的次数,缺省为在整个字符串中查找
... print("hello world".count('o', 7, 10))
>>> # 在索引[n , y)之间查找元素,缺省为[:]返回元素的索引,如果没找到返回-1
... print("hello world".find('e'))
>>> print("hello world".find('o', 0, 2))
-1
>>> # 在[n, y)之间找元素的索引值,没找到会报错
... print("hello world".index('o'))
>>> print("hello world".index('e', 0, 5))

3.4 字符串判断

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
>>> # 判断字符串是否以某个元素开始
... print('helloworld'.startswith('h'))
True
>>> # 判断字符串的的从[n,y)的索引之间是否以某个字符结尾,返回值为布尔值
... print("hello world".endswith('e', 0, 2))
True
>>> # 判断是否是只有数字或字母
... print('abc123'.isalnum())
True
>>> # 判断是否只含有字母
... print('abc'.isalpha())
True
>>> # 判断字母是否都是小写
... print("Hello".islower())
False
>>> # 判断字符是不是空格
... print(" ".isspace())
True
>>> # 判断是不是字符串是不是标题(单词首字母是不是大写)
... print("Hello World".istitle())
True

3.5 字符串格式化

 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
>>> # 字符串居中,规定字符串的总长度,不够用其他字符补齐,默认是空格
... print("hello world".center(20, "#"))
####hello world#####
>>> # 把字符串中的\t替换为n个空格
... print("hello\tworld".expandtabs(tabsize=20))
hello               world
>>> print('#'.join("hello world"))
h#e#l#l#o# #w#o#r#l#d
>>> # 规定输出字符的长度,并且左对齐,不足部分用指定字符补齐
... print("hello world".ljust(20, "#"))
hello world#########
>>> # 规定输出字符的长度,并且右对齐,不足部分用指定字符补齐
... print("hello world".rjust(20, "#"))
#########hello world
>>> # 去除字符串左边的的空格
... print(' hello'.lstrip())
hello
>>> # 去除字符串右边的的空格
... print('hello '.rstrip())
hello
>>> # 去除字符串两边的的空格
... print(' hello '.strip())
hello
>>> # 指定字符串的长度,不够在前面补0
... print("123".zfill(5))
>>> # 字符串的拼接
... print('hello ' + 'world')
hello world
>>> # 字符串重复
... print('hello ' * 3)
hello hello hello

3.6 字符串的赋值

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
>>> s = 'hello world'   # 单引号
>>> print(s)
hello world
>>> s = "hello world"   # 双引号
>>> print(s)
hello world
>>> s = """hello    # 三引号
... world
... !!!"""
>>> print(s)
hello
world
!!!
>>> s = 'hello\tworld' # 转义序列
>>> print(s)
hello   world
>>> s = r'hello\tworld'  # 原始字符串,不进行转义
>>> print(s)
hello\tworld

3.7 字符串转换

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> x = 123
>>> x = str(x) # 把一串字符转为字符串
>>> print(x)
123
>>> print(type(x))
<class 'str'>
>>> print(chr(65))  # ASCII值转字符
A
>>> print(ord('B')) # 字符转ASCII值
66

4. 字符串格式化

4.1 格式化表达式

4.1.1 基于C语言的printf模型
1
2
3
>>> name = "Kobe"
>>> print('%s is %d years old.' % (name, 41))
Kobe is 41 years old.
4.1.2 基于字典的格式化表达式
1
2
>>> print('%(name)s is %(age)d years old.' % {'name':'Kobe', 'age':41})
Kobe is 41 years old.

4.2 格式化方法调用

4.2.1 通过相对位置替换目标
1
2
>>> print('{} is {} years old.'.format('Kobe',41))
Kobe is 41 years old.
4.2.2 通过位置替换目标
1
2
3
4
>>> print('{0} is {1} years old.'.format('Kobe',41))
Kobe is 41 years old.
>>> print('{1} is {0} years old.'.format(41, 'Kobe'))
Kobe is 41 years old.
4.2.3 通过关键字替换目标
1
2
>>> print('{name} is {age} years old.'.format(name='Kobe',age=41))
Kobe is 41 years old.

三、列表

1. 列表的特点

  1. 任意类型的对象的位置相关的有序集合
  2. 大小可变,可以修改
  3. 支持任意嵌套

2. 列表操作

2.1 计算列表长度

1
2
3
>>> l = ['Tom','Bob',123,['boy','girl']]
>>> len(l)
4

2.2 列表拼接

1
2
>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]

2.3 列表重复

1
2
>>> ['hello'] * 3
['hello', 'hello', 'hello']

3. 列表索引

1
2
3
4
5
6
>>> l[-1] # 负索引
['boy', 'girl']
>>> l[2]  # 正索引
123
>>> l[3][1] # 两次索引
'girl'

4. 列表切片

1
2
3
4
5
6
7
8
>>> l[:]
['Tom', 'Bob', 123, ['boy', 'girl']]
>>> l[1:3]
['Bob', 123]
>>> l[-2:-1]
[123]
>>> l[-2:]
[123, ['boy', 'girl']]

5. 列表方法

5.1 添加

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 在尾部插入一项
>>> l = ['刘备','关羽','张飞']
>>> l.append('诸葛亮')
>>> l
['刘备', '关羽', '张飞', '诸葛亮']
# 把一个列表添加到另一个列表末尾
>>> L1 = ['刘备','关羽','张飞']
>>> L2 = ['姜维','诸葛亮']
>>> L1.extend(L2)
>>> L1
['刘备', '关羽', '张飞', '姜维', '诸葛亮']
# 在指定索引位置插入元素
>>> l
['刘备', '关羽', '张飞']
>>> l.insert(1,'马超')
>>> l
['刘备', '马超', '关羽', '张飞']

5.2 删除

 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
# 删除所有元素
>>> l.clear()
>>> l
[]
# 根据索引删除元素并打印删除的元素
>>> l
['刘备', '马超', '关羽', '张飞']
>>> l.pop()    # 无参数删除最后一个
'张飞'
>>> l
['刘备', '马超', '关羽']
>>> l.pop(1)  # 指定索引删除
'马超'
>>> l
['刘备', '关羽']
# 删除指定元素
>>> l = ['刘备','关羽','张飞']
>>> l.remove("关羽")
>>> l
['刘备', '张飞']
# 使用del语句删除指定元素
>>> l = ['刘备','关羽','张飞']
>>> del l[1]
>>> l
['刘备', '张飞']

5.3.拷贝

1
2
3
>>> l1 = l.copy()
>>> l1
['刘备', '关羽', '张飞']

5.4 查找

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 统计某个元素出现的次数
>>> l.count('关羽')
# 查找[a,b)之间某元素的索引值
>>> L1
['刘备', '关羽', '张飞', '姜维', '诸葛亮']
>>> L1.index('关羽')
>>> L1.index('关羽',2,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: '关羽' is not in list

5.4 排序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 倒序
>>> l = ['b','B','a','h']
>>> l.reverse()
>>> l
['h', 'a', 'B', 'b']
# 升序
>>> l.sort()
>>> l
['B', 'a', 'b', 'h']
# 降序
>>> l.sort(reverse=True)
>>> l
['h', 'b', 'a', 'B']

四、元组

1. 元组的特点

  1. 不可变性
  2. 支持嵌套

2. 元组操作

2.1 计算元组长度

1
2
3
>>> t = (1,2)
>>> len(t)
2

2.2 列表拼接

1
2
>>> (1,2)+(3,4)
(1, 2, 3, 4)

2.3 列表重复

1
2
>>> (1,2)*3
(1, 2, 1, 2, 1, 2)

3. 元组的方法

1
2
3
4
>>> t.count(1)
1
>>> t.index(1)
0

元组的特殊语法

定义只有一个元素的元组

1
x = (40,)

创建元素元素的圆括号可以省略

1
2
3
>>> T = 'name', 'age'
>>> T
('name', 'age')

五、字典

1. 字典的特点

  1. 通过键来存储对象
  2. 无序的集合
  3. 可变性
  4. 通过散列表实现

2. 字典的创建

2.1 方法一:先创建再赋值

1
2
3
4
5
>>> person = {}
>>> person['name'] = 'Bob'
>>> person['job'] = 'dev'
>>> person
{'name': 'Bob', 'job': 'dev'}

2.2 方法二:创建时同时赋值

1
2
3
4
5
6
7
>>> d = {'name':'Tom','job':'IT'}
>>> d
{'job': 'IT', 'name': 'Tom'}
>>> d['age'] = 18
>>> d['sex'] = 'boy'
>>> d
{'job': 'IT', 'sex': 'boy', 'name': 'Tom', 'age': 18}

2.3 方法三:通过dict函数创建

1
2
3
4
5
6
7
8
# 传递键值
>>> D = dict(name='Bob', job='dev')
>>> D
{'name': 'Bob', 'job': 'dev'}
# 使用zip
>>> D = dict(zip(["name", "job"], ["Bob", "dev"]))
>>> D
{'name': 'Bob', 'job': 'dev'}

3. 字典索引

1
2
3
4
5
>>> d = {'name':'Tom','job':'IT'}
>>> d
{'name': 'Tom', 'job': 'IT'}
>>> d['name']
'Tom'

4. 键的排序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> d.keys()
dict_keys(['name', 'job'])
>>> list(d.keys())
['name', 'job']
>>> Ks = list(d.keys())
>>> Ks.sort()
>>> for k in Ks:
... print(k,'-->',d[k])
...
job --> IT
name --> Tom

5. 判断一个键是否存在

1
2
3
4
5
>>> d
{'name': 'Tom', 'job': 'IT'}
# 判断一个键是否存在
>>> 'name' in d
True

6. 字典的方法

6.1 删除

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# 清空字典 clear
>>> d = {'name': 'Tom', 'job': 'IT'}
>>> d.clear()
>>> d
{}
# 删除指定键 pop
>>> d.pop('sex','not find')
'not find'
>>> d.pop('name')
'Tom'
# 随机删除键值对,字典为空时报错
>>> d.popitem()
('job', 'IT')
>>> d.popitem()
('name', 'Tom')
>>>
>>> d.popitem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'

6.2 拷贝

1
2
3
4
>>> d = {'name': 'Tom', 'job': 'IT'}
>>> D = d.copy()
>>> D
{'name': 'Tom', 'job': 'IT'}

6.3 创建

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
>>> l = ['name', 'age']
>>> d = {}
>>> d.fromkeys(l,'abc')
{'age': 'abc', 'name': 'abc'}
# 如果键不存在添加一个,如果存在不做更改
>>> d.setdefault('sex','boy') 
'boy'
>>> d
{'job': 'IT', 'sex': 'boy', 'name': 'Tom'}
>>> d.setdefault('sex','girl')
'boy'
>>> d
{'job': 'IT', 'sex': 'boy', 'name': 'Tom'}
# 合并字典,把一个字典加到另一个字典
>>> d1 = {'name': 'Tom', 'job': 'IT'}
>>> d2 = {'sex':'boy'}
>>> d1.update(d2)
>>> d1
{'job': 'IT', 'sex': 'boy', 'name': 'Tom'}

6.4 查找

1
2
3
4
5
6
# 根据键查找值
>>> d = {'name': 'Tom', 'job': 'IT'}
>>> d.get('name')
'Tom'
>>> d.get('sex','not find')
'not find'

6.5 遍历字典

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> d.items()
dict_items([('job', 'IT'), ('name', 'Tom')])
>>> for k,v in d.items():
... print(k,v)
...
job IT
name Tom
>>> for k in d.items():
... print(k)
...
('job', 'IT')
('name', 'Tom')

六、集合

1. 集合的特点

  1. 无序
  2. 唯一
  3. 不可变 集合中的元素不可变

2. 集合的作用

  1. 列表去重
  2. 关系测试:交集、并集、差集

3. 集合创建

1
2
3
set1 = set({1,3,5}) # 第一种方法
set2 = {1,3,5}  # 第二种方法
set3 = set() # 空集合

4. 集合操作

4.1 增

1
2
3
4
5
6
7
8
>>> set1 = set({1,3,5})
>>> set1.add(7)
>>> set1
{1, 3, 5, 7}
# 迭代增加
>>> set1.update('abc')
>>> set1
{1, 3, 5, 7, 'a', 'b', 'c'}

4.1 删除

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 按照元素删除
>>> set1.remove('c')
>>> set1
{1, 3, 5, 7, 'a', 'b'}
# 随机删除
>>> set1.pop()
1
# 情况列表
>>> set1.clear()
>>> set1
set()

5. 关系测试

5.1 交集

1
2
3
4
5
6
>>> set1 = {1,3,5,7,8}
>>> set2 = {2,3,6,7,8}
>>> set1 & set2
{8, 3, 7}
>>> set1.intersection(set2)
{8, 3, 7}

5.2 并集

1
2
3
4
5
6
>>> set1 = {1,3,5,7,8}
>>> set2 = {2,3,6,7,8}
>>> set1 | set2
{1, 2, 3, 5, 6, 7, 8}
>>> set1.union(set2)
{1, 2, 3, 5, 6, 7, 8}

5.3 差集

1
2
3
4
5
6
>>> set1 = {1,3,5,7,8}
>>> set2 = {2,3,6,7,8}
>>> set1 - set2
{1, 5}
>>> set1.difference(set2)
{1, 5}

5.4 反交集

1
2
3
4
>>> set1 ^ set2
{1, 2, 5, 6}
>>> set1.symmetric_difference(set2)
{1, 2, 5, 6}

5.5 子集与超集

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> set1 = {1,2}
>>> set2 = {1,2,3}
>>> set1 < set2
True
>>> set1 > set2
False
>>> set1.issubset(set2)
True
>>> set1.issuperset(set2)
False