学习python的基本数据结构
- python是不区分变量类型的,但是使用时候需要小心
- 如果我们不知道这个什么类型, 可以使用type(变量名)
- python有以下类型:
- int ( integer)
- float
- str (string)
- list
- tuple(元组,不可变)
- dict(dictionary) map
- set
- bool(boolean True/False)
- 变量名命名规则
- 不能以数字开头
- 不能变量名出现空格
- 不能使用如下特殊字符:'",<>/?|()!@#$%^&*~-+
- 考虑到最佳实践(PEP8),变量名最好小写
- 避免使用容易产品视觉错误字符’l’(容易看成1)、 ‘o’(容易看成0) 和’I’(容易看成1)
- 避免使用python有特殊含义字符串,例如"str",“list”
文章目录
1、 数字(Number)
1.1、按照数据类型
- 整数型(integer) : 例如 2,3,100
- 浮点型 (float) : 例如 2.2,.2(代表0.2,零省略了)
1.2、按数字运算方式
-
二元运算
-
一元运算
1.2.1、二元运算
这个就是我们常说的加减乘除,取模,次方
- 加: 2+1 (值为3)
- 减: 2-1 (值为1)
- 除: 3/2 (值为1.5) (保留小数)
- 乘: 2*2 (值为4)
- 整除: 3//2 (值为1)
- 取模: 7%3 (值为3)
- 次方: 2**3 (2^3 等于8)
1.2.2、一元运算
- 赋值运算: 格式为:变量名=值,例如 a=2 (表示将2赋值给a)
友好提示
对于自身参与运算,我们可以简化运算,比如说 a = a + 1, 我们可以简化成 a+=1,支持这样操作有如下
( +=, -=, *= , /=)分别为加赋值,减赋值,乘赋值,除赋值
2、字符串(String)
2.1、如何创建一个字符串
- 字符串可以使用单引号和双引号,python没有说单引号引用是字符,都是作为字符串,例如
- ‘hello’ 和 ”hello“
- 如果字符串中包含单引号,比如说 I’m ,此时我们可以使用双引号可以避免"I’m" 或者 ‘I’m’ (转义)
2.2、String内置一些常用方法和用法
2.2.1、获取字符串的长度
- len(字符串)
- 例如:len(‘hello world’)
2.2.2、获取字符串中某个字符
- 下标从0开始
- 比如获取第一个元素 s[0]
s = 'Hello World'
print(s)
print('获取第一个元素 H ,s[0]=', s[0])
print('获取第二个元素 e,s[1]=', s[1])
print('获取第三个元素 l,s[2]=', s[2])
2.2.3、切割字符(😃
- (注意边界规则:前闭后开)
# 比如说截取第1个元素到最后 'ello World'
print(s[1:])
# 确定上边界,从0到3,但是不包含第3号索引对应元素 'Hel'
s[:3]
# 包含全部,如果不写前后边界, 'Hello World'
s[:]
# 用负数表示从最后往前数, -1 表示最后一个元素, 'd'
s[-1]
# 第三元素表示步长, 2 表示 间隔一个元素 'HloWrd'
print(s[::2])
# 负数表示从后面开始切起,如下效果就是反转 'dlroW olleH'
s[::-1]
2.2.4、字符串是不可变
- 也就是说不能改变字符串中某个字符
- 例如 s[0] = x 将会抛出异常
2.2.5、字符串运算
- 加: 表示两个字符串连接在一起
- 星号: 字符串重复次数
# 拼接字符串 'Hello World concatenate me !'
s + ' concatenate me !'
# 支持 * 操作,表示重复字符串的次数,如下重试5次 'zzzzz'
letter = 'z'
letter*5
2.2.6、内置的方法
- 比如字符串变成大小写,字符串分割
s = 'Hello World concatenate me!'
# 变成大写字符 'HELLO WORLD CONCATENATE ME!'
s.upper()
# 变成小写字符 'hello world concatenate me!'
s.lower()
# 分割字符串成数组,默认空格为分割符: ['Hello', 'World', 'concatenate', 'me!']
array = s.split()
print(array)
2.2.7、格式化字符串
- 打印字符串格式化 {} 作为占位符 ,‘Insert another string with curly brackets: The inserted string’
'Insert another string with curly brackets: {}'.format('The inserted string')
2.2.7.1、连接字符串的方式
- 加号(+)
- f’’ (f-字符串语法)
player = 'Thomas'
points = 33
print('Last night, '+player+' scored '+str(points)+' points.' ) # 表示拼接字符串
print(f'Last night, {player} scored {points} points.') # 字符格式化,采用f-字符串语法
- 加号比较看起比较乱, f-字符串更加清晰一些
2.2.7.2、三种格式化字符串的方法
- 使用最古老的占位符%(百分号)
- 使用字符串的format方法
- python 3.6支持的方法,f-strings
2.2.7.2.1、使用%占位符
- %s表示字符串占位,可以解析出转义字符
- %r 表全部字符都展示(包括转义字符)
- %d 表示整数占位符, 小数部分直接截断
- %5.2f 表示字符串长度最少是5,不足前面补空格, .2f 表示浮点的小数位是2位(四舍五入),小数位不足补0 13.14
示例如下:
# 一个字符, 'I'm going to inject something here.'
print("I'm going to inject %s here. " % 'something')
# 两个占位符 "I'm going to inject some text here, and more text here"
print("I'm going to inject %s text here, and %s text here." % ('some', 'more'))
# 也可以是变量 "I'm going to inject some text here, and more text here"
x, y = 'some', 'more'
print("I'm going to inject %s text here, and %s text here." % (x, y))
# %s表示字符串占位,可以解析出转义字符, %r 表全部字符都展示(包括转义字符)
# He said his name was Fred.
# He said his name was 'Fred'
print('He said his name was %s.' % 'Fred')
print('He said his name was %r.' % 'Fred')
# I once caught a fish this big.
# I once caught a fish 'this \tbig'
print('I once caught a fish %s.' % 'this \tbig')
print('I once caught a fish %r.' % 'this \tbig')
# %s也可以做数字占位符, %d表示整数占位符, 小数部分直接截断
# I wrote 3.75 programs today.
# I wrote 3 programs today.
print('I wrote %s programs today.' % 3.75)
print('I wrote %d programs today.' % 3.75)
# %5.2f 表示字符串长度最少是5,不足前面补空格, .2f 表示浮点的小数位是2位(四舍五入),小数位不足补0 13.14
print('Floating point numbers: %5.2f' %(13.144))
# %1.0f 表示字符长度最少为1, .0f 没有小数位 13
print('Floating point numbers: %1.0f' %(13.144))
# %1.5f 表示字符串长度最少为1, .5f 小数位为5, 13.14400
print('Floating point numbers: %1.5f' %(13.144))
# %10.2f 表示字符串长度最少为10, 不足补空格, 如下需要补8个空格: 13.44
print('Floating point numbers: %10.2f' %(13.444))
#更多详情参考:https://docs.python.org/3/library/stdtypes.html#old-string-formatting
# 多种格式混合使用 First: hi!, Second: 3.14, Third: 'byte!'
print('First: %s, Second: %5.2f, Third: %r' %('hi!', 3.1415, 'bye!'))
2.2.7.2.1、使用字符串format方法
- {} 作为占位符
- 可以使用序号,也可以是变量名
# 一个占位符 This is a string with an insert
print('This is a string with an {}'.format('insert'))
# 指定占位符位置索引替换(从0开始) The quick brown fox
print('The {2} {1} {0}'.format('fox', 'brown', 'quick'))
# 指定变量名, First Object: 1, Second Object: Two, Third Object: 12.3
print('First Object: {a}, Second Object: {b}, Third Object: {c}'.format(a=1, b='Two',c=12.3))
# 变量可以重复使用 'A peny saved is a penny earned.'
print('A %s saved is a %s earned.' %('peny','penny'))
# vs
print('A {p} saved is a {p} earned.'.format(p='penny'))
- 可以对齐方式和不足长度进行补充,{0:=<8} 0代表变量序号,=表示不足时候补充的符号, < 左对齐,8 满足8位长度
# 对齐,填充、精度 {0:8} 第一元素表示,那个变量, 8 表示最小长度,默认情况下,文本左对齐,数字右对齐
print('{0:8} | {1:9}'.format('Fruit','Quantity'))
print('{0:8} | {1:9}'.format('Apples', 3.0))
print('{0:8} | {1:9}'.format('Oranges', 10))
"""
Fruit | Quantity
Apples | 3.0
Oranges | 10
"""
# 可以自定义对齐,<,^,> 表示 左对齐,居中,右对齐
print('{0:<8} | {1:^8} | {2:>8}'.format('Left', 'Center', 'Right'))
print('{0:<8} | {1:^8} | {2:>8}'.format(11, 12, 33))
"""
Left | Center | Right
11 | 12 | 33
"""
# 可以自定义填充符 (只有字符表示对齐标记,有两个字符时候,第一个字符为填充字符,第二对齐标记)
print('{0:=<8} | {1:-^8} | {2:.>8}'.format('Left', 'Center', 'Right'))
print('{0:=<8} | {1:-^8} | {2:.>8}'.format(11, 12, 33))
"""
Left==== | -Center- | ...Right
11====== | ---12--- | ......33
"""
# 数字类似 13.58 'This is my ten-character, two-decimal number: 13.58'
print('This is my ten-character, two-decimal number:%10.2f' % 13.579)
print('This is my ten-character, two-decimal number:{0:10.2f}'.format(13.579))
2.2.7.2.2、使用f-strings
name = 'Fred'
print(f"He said his name is {name}.")
# 使用!r表示显示所有字符,作为字面值, He said his name is 'Fred'
print(f'He said his, name is {name!r}')
# 数字 "result: {value:{width}.{precision}}" , {value:10.4f}, f-strings表示为{value:{10}.{6}}
# 需要 precision 表示所有整数和小数位数总和
num = 23.45678
print("My 10 character, four decimal number is:{0:10.4f}".format(num))
print(f"My 10 character, four decimal number is:{num:{10}.{6}}")
"""
My 10 character, four decimal number is: 23.4568
My 10 character, four decimal number is: 23.4568
"""
# 注意如果小数位不足,f-string不会填充0,如果对小数位特别敏感,不建议使用f-string最新语法
num = 23.45
print("My 10 character, four decimal number is:{0:10.4f}".format(num))
print(f"My 10 character, four decimal number is:{num:{10}.{6}}")
"""
My 10 character, four decimal number is: 23.4500
My 10 character, four decimal number is: 23.45
"""
num = 23.45
print("My 10 character, four decimal number is:{0:10.4f}".format(num))
print(f"My 10 character, four decimal number is :{num:10.4f}")
"""
My 10 character, four decimal number is: 23.4500
My 10 character, four decimal number is : 23.4500
"""
# f-string更多参考:https://docs.python.org/3/reference/lexical_analysis.html#f-strings
3、列表(List)
3.1、创建一个list
# 直接赋值list列表
my_list = [1, 2, 3]
# list 可以包含不同类型值
my_list = ['A string', 23, 100.232, 'l']
3.2、list运算
- 冒号(😃 : 切片
- 星号(*) : 复制翻倍
- 加号(+) : 将两个list合并一起
my_List = ['one', 'two', 'three', 4, 5]
# 获取0号元素 : 'one'
my_list[0]
# 获取1号-->最后元素 ['two','three',4,5]
my_list[1:]
# 0 -> 3 元素 ['one', 'two', 'three']
my_list[:3]
# 使用 '+' 连接list ['one', 'two', 'three', 4, 5, 'new item'], 但是不会改变原来list, 只有做赋值操作才会改变
my_list + ['new item']
# 改变my_list的值
my_list = my_list + ['add new item permanently']
# 使用 '*' 重复元素
my_list * 2
"""
['one',
'two',
'three',
4,
5,
'add new item permanently',
'one',
'two',
'three',
4,
5,
'add new item permanently']
"""
3.3、list基础方法
3.3.1、list的长度
- len(list)
- append 添加元素
- pop 弹出元素
- reverse 反转list元素
# 创建一个list
list1 = [1, 2, 3]
print(list1)
# 在后面添加元素 [1, 2, 3, 'append me!']
list1.append('append me!')
# 弹出元素 0号元素: 1, 还剩余[2,3,'apppend me!']
list1.pop(0)
# 默认弹出 -1号元素(最后一个元素) [2,3]
popped_item = list1.pop()
# 如果访问索引不存在的元素,将会抛出IndexError
new_list = ['a', 'e', 'x', 'b', 'c']
# 反转list元素 ['c','b','x','e','a']
new_list.reverse()
# 排序 sort() 默认按字母升序 ['a', 'b', 'c', 'e', 'x']
new_list.sort()
# 3. list 中包含list [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
lst_1 = [1,2,3]
lst_2 = [4,5,6]
lst_3 = [7,8,9]
matrix = [lst_1, lst_2, lst_3]
3.4、推导方法(形成新的list)
- 语法 [item for item in list]
- 做一些简单处理,直接可以一行搞定
比如说 将list平方之后形成信息list
list1 = [1,2,3,4,5]
square_list = [item**2 for item in list1]
print(square_list)
4、字典或者map(Dictionaries)
- key-value 键值对
4.1、创建dictionary
- 语法: {key:value}
- 获取对应key的值, dict[key]
# 以{}包裹,key:value
my_dict = {"key1": "value1", 'key2': "value2"}
# 获取 key2的对应值:value2
my_dict['key2']
# dictionary 可以存各种类型对象
my_dict = {'key1':123, 'key2':[12,32,22], 'key3':['item0','item1','item2']}
# 获取key3的值 ['item0','item1','item2']
my_dict['key3']
# 获取key3中 0号位置值: item0
my_dict['key3'][0]
4.2、内置的dictionary的方法
- 查看所有key: d.keys()
- 查看所有value: d.values()
- 查询所有键值对: d.items()
# dictionary 内部包含dictionaries
d = {'key1': {'nestkey': {'subnestkey': 'value'}}}
# 获取subnestkey的值
d['key1']['nestkey']['subnestkey']
# 3. dictionary的方法
# 创建一个dictionary
d = {'key1': 1, 'key2': 2, 'key3': 3}
# 获取dictionary的keys
d.keys()
# 获取dictionary value
d.values()
# 获取dictionary 键值对 item, 它是一个key-value的元组(tuple)
d.items()
5、元组(Tuple)
5.1、创建一个元组
- 元组可以认为是一个不能可变的list
- t = (元素1,元素2)
# 1. 构建tuples 使用()
t = (1, 2, 3)
5.2、获取对应元素
- len(t) 长度
- t[0] 获取第一个元素
- t[-1] 获取最后一个元素
- t.index(元素名) 获取元素的索引位置
- t.count(元素名) 获取元素的计数个数
# 检查tuple的长度: 3
len(t)
# tuples中还是可以不同类型对象: ('one',2)
t = ('one', 2)
# 获取第一个元素: 'one'
t[0]
# 获取最后一个元素
t[-1]
# 2. tuple基本方法
# 显示元素的索引位置: 0
t.index('one')
# 显示元素的个数: 1
t.count('one')
5.3、元组元素不可变
- 不能进行元组赋值
# 不能进行赋值操作, 将会抛出 TypeError
t[0] = 'change'
# 不支持添加元素 AttributeError
t.append('nope')
6、不重复集合(Set)
6.1、创建一个set
- set()
# 构建一个Set对象
x = set()
6.2、添加元素
# 添加元素 {1}
x.add(1)
# 添加不同元素 {1,2}
x.add(2)
x.add(1)
# 可以set给list 去重
# 我们可以利用set进行去重,将list1去重: {1,2,3,4,5,6}
list1 = [1,1,2,2,3,4,5,6,1,1]
set(list1)
7. bool(布尔)
- True /False (注意首字母大写)
8、总结
- 无论list和string 都有对应len方法,统计字符长度或元素的个数
- 可变list和string支持 +,*,相关运算
- list和string支持:切割元素和字符串
- python 变量命名是小字母+下划线
参考文档
- https://github.com/Pierian-Data/Complete-Python-3-Bootcamp.git
5732





