Python 基础之数据类型(一)

1、什么是Python:

        Python是一种高级编程语言,具有语法简洁,易于理解和学习、可扩展等特点。并且具有丰富的标准库和第三方库,可以用于Web开发、数据科学、人工智能、游戏开发等多个领域。而且可以也是跨平台的编程语言,可以在Windows、Mac、Linux等不同操作系统上运行。

2、数据类型:

       数据类型指的是变量可以存储的数据的类型。

   数值类型

名称描述
int(整数)数学概念中的整数。
float(浮点数)数学概念中的实数。
complex(复数)数学概念中的复数。

   序列类型

名称描述
str(字符串)字符串是字符的序列表示,用来表示文本信息。
list(列表)列表用来表示有序的可变元素集合。例如表示一个有序的数据组。
tuple(元组)元组用来表示有序的不可变元素集合。

   散列类型

名称描述
set(集合)数学概念中的集合,无限不重复元素的集合。
dict(字典)字典是无序键值对的集合。用来表示有关联的数据,例如表示一个人的基本信息。

   其他类型

名称描述
bool(布尔型)bool型数据只有两个元素,True表示真,False表示假。用来表示条件判断结果。
NoneNone表示空。

3、数值类型

1. 整数

Python中整数用 int 表示,与数学中的整数概念一致。

max = 99
print(max)
运行结果: 99

详解:
max是变量名, = 是赋值运算符,99是值。就是把 99 赋值给 max 变量

变量命名规则:
1.由大小写字母A-Za-z,数字0-9和下划线_组成;
2.不能以数字开头;
3.不能是关键字;
4.变量名大小写敏感;

正确案例:
demo = 12
demo1 = 21
Demo = 20
DE_m1o = 30

错误案例:
1demo = 12

Python官方占用了一些变量名作为程序的关键字,总共35个,这些关键字不能作为自定义变量名使用。

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']

2. 赋值运算符

Python中 = 是赋值运算符,而不是数学意义上的等于号。

Python解释器会先计算 = 右边的表达式,然后将结果复制给 = 左边的变量。

正确案例:
max = 12
res = max + max
print(res)
运行结果: 24

min = 100
res = max + min
print(res)
运行结果: 112

age = 21
res = max + min + age
print(res)
运行结果: 133

res = max * min / age
print(res)
运行结果: 57.142857142857146

res = 89 - age + max
print(res)
运行结果: 80

3. type函数和print函数 

Python提供了内建函数 type 用来查看值或者变量的类型。

只需要将变量或者值作为参数传入type函数即可。

print(type(1))
运行结果: <class 'int'>

print(type(100))
运行结果: <class 'int'>

age = 12
print(type(age))
运行结果: <class 'int'>

print函数用来在屏幕上输出传入的数据的字符串表现形式,是代码调试最重要的函数。

age = 12
print(age)
运行结果: 12

print(type(age))
运行结果: <class 'int'>
# 注意交互式输出和print函数输出的区别

4. 整数的常见表示形式;

Python中整数最常见的是10进制整数,也有二进制,八进制和十六进制。

a = 10  # 十进制
print('a的类型为:', type(a), a)
运行结果: a的类型为: <class 'int'> 10

b = 0b1110  # 二进制
print('b的类型为:', type(b),b)
运行结果: b的类型为: <class 'int'> 14

c = 0o57    # 八进制
print('c的类型为:', type(c),c)
运行结果: c的类型为: <class 'int'> 47

d = 0xa5c   # 十六进制
print('d的类型为:', type(d), d)
运行结果: d的类型为: <class 'int'> 2652

5. 整数的取值范围

Python中整数取值范围是[-无穷,无穷],实际取值范围受限于运行 Python 程序的计算机内存大小。

2. 浮点数

Python中浮点数数用 float 表示,与数学中的实数概念一致,也可以理解为有小数。

1.浮点数的表现形式 

max = 0.1
print(type(max))
运行结果: <class 'float'>

max1 = 1.2
print(type(max1))
运行结果: <class 'float'>

max2 = 11.2
print(type(max2))
运行结果: <class 'float'>

max3 = 74.
print(type(max3))
运行结果: <class 'float'>

max4 = .87
print(type(max4))
运行结果: <class 'float'>

max5 = -2.3
print(type(max5))
运行结果: <class 'float'>

max6 = 9.5e-2
print(type(max6))
运行结果: <class 'float'>

 浮点数可以表示所有的整数数值,Python为何要同时提供两种数据类型?

因为相同的操作整数要比浮点数快5-20倍

2.数学运算符

运算符描述
+加法 1+1
-减法 3-2
*乘法 9*9
/除法 9/3,除法运算后的结果一定为float类型
//整除 10/3,也称为地板除向下取整
%取模 10%3,表示10除以3取余数
**幂次 2**3,表示2的3次幂
()括号 ,括号内的表达式先运算 (1+2)* 3

注意一个浮点数和一个整数进行运算后的结果一定为浮点数;

res = 3.4 + 4
print(res)
运行结果: 7.4

res = 20 - 3
print(res)
运行结果: 17

res = 3 * 3
print(res)
运行结果: 9

res = 20 / 3 #除法运算的结果一定为float类型
print(res)
运行结果: 6.666666666666667

res = 20 // 3 #地板除,向下取整
print(res)
运行结果: 6

res = 20 % 3 #取模,向下取余数
print(res)
运行结果: 2

res = 2 ** 3 #幂次,表示2的3次幂
print(res)
运行结果: 8

res = 2 + (1+3) #括号运算符,优先计算括号内表达式
print(res)
运行结果: 8

3.组合赋值运算符

赋值运算符与算术运算符可以组合使用,注意算术运算符要写在前面且中间不能有空格。

运算符描述
=等于(简单的赋值)
+=加等于
-=减等于
*=乘等于
/=除等于
%=取余等于
**=幂等于
//=取整除等于

赋值运算符与算术运算符可以组合使用,注意算术运算符要写在前面且中间不能有空格。

res = 4
res += 5
print(res) # 等同于res = res + 5
运行结果: 9

res1 = 4
res1 -= 3
print(res1) # 等同于res1 = res1 - 3
运行结果: 1

res2 = 2
res2 *= 10
print(res2) # 等同于res2 = res2 * 10
运行结果: 20

res3 = 10
res3 /= 2
print(res3) # 等同于res3 = res3 / 2
运行结果: 5.0

res5 = 30
res5 **= 10
print(res5) # 等同于res5 = res5 ** 10
运行结果: 590490000000000

res6 = 30
res6 %= 20
print(res6) # 等同于res6 = res6 % 20
运行结果: 10

res7 = 20
res7 //= 6
print(res7) # 等同于res7 = res7 // 6
运行结果: 3

4.浮点数和整数的相互转化

int,float是 Python 的内置函数,通过它们可以对浮点数类型和整数类型相互转化。

print(int(2.4))
运行结果: 2
res = 2.9
print(int(res))
运行结果: 2
print(type(res))
运行结果: <class 'float'>
# 转化为整数,通过调用int函数,提取浮点数的整数部分;

print(float(2))
运行结果: 2.0
res = 100
print(float(res))
运行结果: 100.0
print(type(res))
运行结果: <class 'int'>
# 转化为浮点数,通过调用float函数,将整数转化为小数部分为0的浮点数;

3. 复数

复数在 Python 中使用 complex 表示;

a = 12.3+4j
print('a的类型为:', type(a))
运行结果: a的类型为: <class 'complex'>
print(a.real)
运行结果: 12.3
print(a.imag)
运行结果: 4.0

4、序列类型

序列类型用来表示有序的元素集合。

1. 字符串

Python 中字符串用 str 表示,字符串是使用单引号,双引号,三引号包裹起来的字符的序列,用来表示文本信息。

使用单引号和双引号进行字符串定义没有任何区别,当要表示字符串的单引号时用双引号进行定义字符串,反之亦然。

一对单引号或双引号只能创建单行字符串,三引号可以创建多行表示的字符串。三双引号一般用来做多行注释,表示函数,类定义时的说明。

1.1 字符串的定义

max = 'a'
max1 = "1"
max2 = """Ab"""
max3 = '''
       TEST
       '''
max4 = """
      TEST
      """
max5 = '' #定义空字符串

print(max,type(max))
运行结果: a <class 'str'>

print(max1,type(max1))
运行结果: 1 <class 'str'>

print(max2,type(max2))
运行结果: Ab <class 'str'>

print(max3,type(max3))
运行结果: TEST
        <class 'str'>

print(max4,type(max4))
运行结果:     TEST
       <class 'str'>

print(max5,type(max5))
运行结果:  <class 'str'>

1.2 字符串的索引

任何序列类型中的元素都有 索引用来表示它在序列中的位置。索引使用整数来表示。

通过 索引可以获取字符串中的单个字符

语法如下:

str[index]
res = 'abcdefghijklmnopqrstuvwxyz'
print(res[0])
运行结果: a

print(res[-1])
运行结果: z

1.3 字符串的切片

获取序列中的子序列叫切片。字符串的切片就是获取字符串的子串。

字符串切片的语法如下:

str[start:end:step]
start表示起始索引,end表示结束索引,step表示步长。
res = 'abcdefghijklmnopqrstuvwxyz'
print(res[1:4])
运行结果: bcd
含义: 包头不包尾

print(res[1:])
运行结果: bcdefghijklmnopqrstuvwxyz
含义: 第2个开始切到末尾

print(res[:])
运行结果: abcdefghijklmnopqrstuvwxyz
含义: 切全部

print(res[:-1])
运行结果: abcdefghijklmnopqrstuvwxy
含义: 第1个开始切到倒数第2个

print(res[2:-2])
运行结果: cdefghijklmnopqrstuvwx
含义: 第3个开始切到倒数第2个

res = 'abcdefghijklmnopqrstuvwxyz'
print(res[::2])
运行结果: acegikmoqsuwy
含义: 切全部,但是要隔2个切一下

print(res[1::3])
运行结果: behknqtwz
含义: 从第2个开始切到最后。但是要隔3个切一下

res = 'abcdefghijklmnopqrstuvwxyz'
print(res[::-1])
运行结果: zyxwvutsrqponmlkjihgfedcba
含义: 切全部,但是要从最后,隔1个切一下(倒序)

1.4 字符串拼接

Python 中可以通过 拼接两个字符串;

res = '123'
print(res + '456')
运行结果: 123456

res = 'abc'
res1 = 'def'
print(res + res1)
运行结果: abcdef

res = '123'
res1 = ''
res2 = '456'
print(res + res1 + res2)
运行结果: 123456

print('-' * 10)
运行结果: ----------

1.5 字符串常用方法

通过内建函数 dir 可以返回传入其中的对象的所有方法名列表。

print(dir(str))
运行结果: ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

 通过内建函数 help 可以返回传入函数的帮助信息。

print(help('abc'.join))
运行结果: Help on built-in function join:

join(iterable, /) method of builtins.str instance
    Concatenate any number of strings.
    
    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.
    
    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

1.6 字符串和数值的相互转化

1 和 '1'不同,1.2和 '1.2'也不相同,但是它们可以相互转化;

print(type(int('1')),int('1'))
运行结果: <class 'int'> 1

print(type(str(1)),str(1))
运行结果: <class 'str'> 1

res = '1'
print(type(int(res)),int(res))
运行结果: <class 'int'> 1

res = 1
print(type(str(res)),str(res))
运行结果: <class 'str'> 1

res = 1.2
print(type(str(res)),str(res))
运行结果: <class 'str'> 1.2

res = '1.3'
print(type(int(res)),int(res))
含义: 浮点数的 字符串 不能抓换成 整数
运行结果: ValueError: invalid literal for int() with base 10: '1.3'

1.7 转义符

在需要在字符中使用特殊字符时,python 用反斜杠  \ 转义字符。

常用转义字符如下表:

(在行尾时)续行符
\\反斜杠符号
\'单引号
\"双引号
\a响铃
\n换行
\t横向制表符
\r回车
\f换页
print('ab\\cd')
运行结果: ab\cd
含义: 输出 单斜杠 本身

print('ab\'cd')
运行结果: ab'cd
含义: 输出 ' 本身

print('ab\"cd')
运行结果: ab"cd
含义: 输出 " 本身

print('ab\acd')
运行结果: abcd
含义: 响铃

print('ab\ncd')
运行结果: ab
cd
含义: 换行

print('ab\tcd')
运行结果: ab	cd
含义: 制表符

print('ab\rcd')
运行结果: cd
含义: 回车

print('ab\fcd')
运行结果: abcd
含义: 换页

1.8 字符串格式化

在实际工作中经常需要动态输出字符。

.format 函数格式化

基本语法:

<模板字符串>.format(<逗号分隔的参数>)

res = '2'
print('1{}3'.format(res))
运行结果: 123
print('a{0}{1}'.format('b','c'))
运行结果: abc
print('现在时间:{time}'.format(time='21:42'))
现在时间:21:42
# 当format中的参数使用位置参数提供时,{}中可以填写参数的整数索引和参数一一对应

1.9 字符串替换

.replace 替换

基本语法:

变量名.replace('需要替换的参数','替换的参数')

1、简单替换
re1 = '你好呀!'
print(re1.replace('!','?')) # 用 ?去替换 !
运行结果:
你好呀?

2、高级替换
import re
case = 'hello #user#' #user#需要替换的参数
args = re.findall('#(.+?)#',case) # 使用 findall 找到所有符合 #(.+?)#的参数;
print(args)
for arg in args: # 进行循环 
    print(arg)
    print(case.replace('#{}#'.format(str(arg)),'word')) # 使用 replace 进行替换

运行结果:
['user']
user
hello word

2. 列表

Python 中列表 list 用来表示任意元素的序列,元素可以是任意数据类型,序列中的元素可以增,删,改。

2.1 列表的定义

列表由一对中括号进行定义,元素与元素直接使用逗号隔开。

res = []
res1 = [1,[]]
res2 = ['1',[]]
res3 = ["1",[]]
res4 = [1.3,["1",1],["v","a",["q","r"]]]
res5 = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name']


print(type(res),res)
运行结果: <class 'list'> []
print(type(res1),res1)
运行结果: <class 'list'> [1, []]
print(type(res2),res2)
运行结果: <class 'list'> ['1', []]
print(type(res3),res3)
运行结果: <class 'list'> ['1', []]
print(type(res4),res4)
运行结果: <class 'list'> [1.3, ['1', 1], ['v', 'a', ['q', 'r']]]
print(type(res5),res5)
运行结果: <class 'list'> [{'test_id': 'sgdfhdjbvhgeskdnsjkf'}, 'name']

2.2 列表的拼接

像字符串一样,列表之间可以进行加法运算实现列表的拼接,列表可以和整数进行乘法运算实现列表的重复。

res = [1,2,3]
res1 = [4,5,6]
print(res + res1)
运行结果: [1, 2, 3, 4, 5, 6]

res2 = ['a','b','c']
res3 = ['d']
print(res2 + res3)
运行结果: ['a', 'b', 'c', 'd']

res4 = [1,[]]
print(res4 * 3)
运行结果: [1, [], 1, [], 1, []]

2.3 列表的索引和切片

注意:索引 和 切片与字符串 操作一致

注意嵌套列表的元素获取

res = [1,"a",[2,["v"],[123],'b']]
print(res[1])
运行结果: a

print(res[2])
运行结果: [2, ['v'], [123], 'b']

print(res[2][2])
运行结果: [123]

2.4 列表的常用操作

Python 中的列表操作非常灵活,是非常重要和经常使用的数据类型。

2.4.1 修改元素

列表的中的元素可以进行修改,只需使用索引赋值即可。

res = [1,2,3,["a","b","c"]]
res[2] = "b"
print(res)
运行结果: [1, 2, 'b', ['a', 'b', 'c']]

res[3] = "d"
print(res)
运行结果: [1, 2, 'b', 'd']
含义: 为啥运行的结果是 [1, 2, 'b', 'd'],因为索引3的位置,是一个嵌套的列表,并不是一个单独的列表。

2.4.2 增加元素

1.在列表末尾添加元素;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name']
res.append('user')
print(res) #如果print("res.append('user')")会返回None
运行结果: [{'test_id': 'sgdfhdjbvhgeskdnsjkf'}, 'name', 'user']


2.在列表指定位置添加元素;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name']
res.insert(0,{'user1':'max'}) # 0表示索引,位置从0开始;
print(res)
运行结果: [{'user1': 'max'}, {'test_id': 'sgdfhdjbvhgeskdnsjkf'}, 'name']


3.扩展列表,添加可迭代的元素;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name']
res.extend(res) #在方法添加添加 res变量名;
print(res)
运行结果: [{'test_id': 'sgdfhdjbvhgeskdnsjkf'}, 'name', {'test_id': 'sgdfhdjbvhgeskdnsjkf'}, 'name']

2.4.3 删除元素

1.pop() 没有指定索引默认删除最后一个元素;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name','jenkins_home2']
print(res.pop())
运行结果: jenkins_home2

2.pop(index=1) 删除指定索引的元素,并返回该元素;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name','jenkins_home2']
print(res.pop(1))
运行结果: name

3.remove(value) 在方法内执行元素删除,如果不存在元素就报错;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name','jenkins_home','jenkins_home1','jenkins_home2']
res.remove('name')
print(res)
运行结果: [{'test_id': 'sgdfhdjbvhgeskdnsjkf'}, 'jenkins_home', 'jenkins_home1', 'jenkins_home2']

4.clear() 清空列表;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name','jenkins_home','jenkins_home1','jenkins_home2']
res.clear()
print(res)
运行结果: []

2.5 列表的其他方法

1. count() 统计元素出现的次数;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name','jenkins_home','jenkins_home','jenkins_home']
print(res.count('jenkins_home'))
运行结果: 3

2. index() 返回列表中指定value的索引,不存在则报错;
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name','jenkins_home','jenkins_home','jenkins_home']
print(res.index('name'))
运行结果: 1

3. reverse() 翻转列表元素顺序
res = [{'test_id':'sgdfhdjbvhgeskdnsjkf'},'name','jenkins_home','jenkins_home','jenkins_home']
res.reverse()
print(res)
运行结果: ['jenkins_home', 'jenkins_home', 'jenkins_home', 'name', {'test_id': 'sgdfhdjbvhgeskdnsjkf'}]


4.sort() 对列表进行排序,默认按照从小到大的顺序,当参数reverse=True时,从大到小。
注意列表中的元素类型需要相同,否则抛出异常。
res = ['name','jenkins_home','jenkins_home','jenkins_home']
res.sort(reverse=True)
print(res)
运行结果: ['name', 'jenkins_home', 'jenkins_home', 'jenkins_home']

res = ['name','jenkins_home','jenkins_home','jenkins_home']
res.sort(reverse=False)
print(res)
运行结果: ['jenkins_home', 'jenkins_home', 'jenkins_home', 'name']

2.6 字符串和列表的转换

字符串是字符组成的序列,可以通过 list函数将字符串转换成单个字符的列表。

1. 字符串转换成列表
str1 = 'name'
print(type(str1))
执行结果: <class 'str'>

print(list(str1))
执行结果: ['n', 'a', 'm', 'e']

print(''.join(str1))
执行结果: name
通过 join 的方式对列表进行拼接;

2. 列表转换成字符串
list1 = ['name','jenkins_home','jenkins_home','jenkins_home']
print(type(list1))
运行结果: <class 'list'>

print(str(list1))
运行结果: ['name','jenkins_home','jenkins_home','jenkins_home']

3. 元组

Python中元组 tuple 表示任意元素的序列,元素可以是任意数据类型,序列中的元素不能增,删,改,可以说元组就是不可变的列表。

3.1 元组的定义

元组通过一对小括号进行定义,元组之间使用逗号隔开。

res = () #空元祖
print(type(res))
运行结果: <class 'tuple'>

res1 = ('dcpp',) #字符串
print(type(res1))
运行结果: <class 'tuple'>

res2 = (1,2,3,4,5) # int
print(type(res2))
运行结果: <class 'tuple'>

res3 = (['test',{'name'},['dcpp']],) #列表
print(type(res3))
运行结果: <class 'tuple'>

res4 = ('anaconda3',) #元祖
print(type(res4))
运行结果: <class 'tuple'>

3.2 元组的索引和切片

序列的索引和切片完全一致,参加字符串。

3.2 元组的常用方法

元组的元素不能 增删改。

元组只有两个公有方法 count,index 用法与列表相同。

res = ('test','name')
print(res.index('name')) #根据 value 返回对应的索引位置
运行结果: 1

print(res.count('name')) #统计元素出现的次数
运行结果: 1

3.3 len函数

Python内建函数 len 可以获取对象中包含的元素个数;

res = ('B','d','a',{"name":"max","user": "min"},["a","b","c",[1,2,3]])
print(len(res))
运行结果: 5
为啥是5个呢!因为
'B','d','a' 算3个元素。
{"name":"max","user": "min"} 算1个元素。
["a","b","c",[1,2,3]] 算1个元素。

5、散列类型

散列类型用来表示无序集合。

1. 集合

Python中集合 set 类型与数学中的集合类型一致,用来表示无序不重复元素的集合。

1.1 集合定义

集合使用一对大括号 {} 进行定义,元素直接使用逗号隔开。

集合中的元素必须是不可变类型。

res = {1,2,3,4,5} # 集合中元素必须是不可变类型
print(type(res),res)
运行结果: <class 'set'> {1, 2, 3, 4, 5}

res1 = {'a','b','c'} # 集合中元素必须是不可变类型
print(type(res1),res1)
运行结果: <class 'set'> {'b', 'a', 'c'}

res2 = {'test'} # 集合中元素必须是不可变类型
print(type(res2),res2)
运行结果: <class 'set'> {'test'}


定义空集合是 set()
res3 = set()
print(type(res3),res3)
运行结果: <class 'set'> set()

使用 {} 是字典
res4 = {}
print(type(res4),res4)
运行结果: <class 'dict'> {}

1.2 集合的常用操作

1.2.1 添加元素

集合添加元素常用函数有两个:add 和 update;

1. add(value) 向集合中添加元素,如果集合中不存在则添加;
res = {1,2,3,4,'user','age',2.3}
res.add('test')
print(res)
运行结果: {1, 2, 3, 4, 2.3, 'test', 'user', 'age'}

2. update({value,value1,value2}) 向集合中添加多个元素,如果集合中不存在则添加;
res = {1,2,3,4,'user','age',2.3}
res.update({'demo','users'}) # 使用update添加元素时,要使用{},否则添加的元素会变成单个元素;
print(res)
运行结果: {1, 2, 3, 4, 2.3, 'demo', 'users', 'user', 'age'}

3. update(value,value1)
res = {1,2,3,4,'user','age',2.3}
res.update('demo','users') # 添加元素时,未使用 {},添加的元素会变成单个元素;
print(res)
运行结果: {1, 2, 3, 4, 2.3, 'd', 'm', 'age', 'user', 's', 'e', 'u', 'r', 'o'}

4. update({'keys':'values'})
res = {1,2,3,4,'user','age',2.3}
res.update({'demo':'users'}) # 添加元素时,如果添加的是 键值对 ,只会把 键 添加到集合内;
print(res)
运行结果: {1, 2, 3, 4, 2.3, 'age', 'demo', 'user'}

1.2.2 删除元素

集合删除元素常用函数有: pop、remove、discard、clear;

1. pop() 随机删除集合中一个元素,并返回集合中的元素;
res = {1,2,3,4,'user','age',2.3}
res.pop()
print(res)
运行结果: {2, 3, 4, 2.3, 'user', 'age'}

2. remove(value) 指定删除集合中的元素,存在就删除,不存在就报错。并返回集合中的元素;
res = {1,2,3,4,'user','age',2.3}
res.remove(2.3)
print(res)
运行结果: {2, 3, 4, 'user', 'age'}

3. discard(value) 指定删除集合中的元素,存在就删除,不存在不报错。并返回集合中的元素;
res = {1,2,3,4,'user','age',2.3}
res.discard('age')
print(res)
运行结果: {2, 3, 4, 'user'}

4. clear() 清空集合,并返回 集合类型 set()
res = {1,2,3,4,'user','age',2.3}
res.clear()
print(res)
运行结果: set()

1.2.3 集合去重

集合具有天生去重的性质,因此可以利用它来去除序列中的重复元素;

1. 集合去重;
res = {1,2,3,4,'user','age',2.3,1,2,3,4,2.3}
print(res)
运行结果: {1, 2, 3, 4, 2.3, 'age', 'user'}

2. 元祖类型去重
res = (1,2,3,4,'user','age',2.3,1,2,3,4,2.3)
print(set(res)) # 先把元祖类型转换成集合类型,就ok啦!
运行结果: {1, 2, 3, 4, 2.3, 'age', 'user'}

1.2.4 集合运算

数学符号Python运算符含义定义
&交集获取属于 A 且属于B 的元素所组成的集合叫做AB的交集
|并集一般地,由所有属于集合A或属于集合B的元素所组成的集合,叫做AB的并集
-或\-相对补集/差集A-B,取在A集合但不在B集合的项
^对称差集/反交集A^B,取只在A集合和只在B集合的项,去掉两者交集项

交集

既取属于集合A和又属于集合B的项组成的集合叫做AB的交集;

含义:  就是返回两个集合里面的重复的元素;

res = {1,2,3,4,'user','age','lower',2.3,1,2,3,4,2.3}
res1 = {'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',1,2,3,4,5,2.3}
print(res & res1)
运行结果: {1, 2, 3, 4, 'lower', 2.3}

并集

集合A和集合B的所有元素组成的集合称为集合A与集合B 的并集;

含义:就是把两个集合里面的重复的元素去掉,并返回不重复的元素;

res = {1,2,3,4,'user','age','lower',2.3,1,2,3,4,2.3}
res1 = {'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',1,2,3,4,5,2.3}
print(res | res1)
运行结果: {1, 2, 3, 4, 'age', 2.3, 5, 'replace', 'lower', 'user', 'lstrip', 'ljust', 'rfind', 'partition', 'maketrans'}

补集

取在集合A中不在集合B中的项组成的集合称为A相对B的补集;

含义:以集合A为准,返回不在集合B里面的元素;

res = {1,2,3,4,'user','age','lower',2.3,1,2,3,4,2.3}
res1 = {'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',1,2,3,4,5,2.3}
print(res - res1)
运行结果: {'age', 'user'}

对称差集

取不在集合AB交集里的元素组成的集合称为对称差集,也叫反交集;

含义:获取两个集合里面没有的元素;

res = {1,2,3,4,'user','age','lower',2.3,1,2,3,4,2.3}
res1 = {'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',1,2,3,4,5,2.3}
print(res1 ^ res)
运行结果: {'rfind', 5, 'age', 'ljust', 'user', 'partition', 'maketrans', 'replace', 'lstrip'}

2. 字典

因为集合无序,因此不能很便捷的获取特定元素。利用集合元素不重复的特性,使集合中的元素映射值组成键值对,再通过键来获取对应的值。

2.1 字典的定义

Python中的字典 dict 数据类型就是键值对的集合,使用一对花括号进行定义,键值对之间使用逗号隔开,键和值使用冒号分割。

字典中的键必须是不可变数据类型,且不会重复,值可以使任意数据类型。

res = {}                      # 空字典
res1 = {
    1: 2,                   # key:数字;value:数字
    2: 'hello',             # key:数字;value:字符串
    ('k1',): 'v1',          # key:元祖;value:字符串
    'k2': [1, 2, 3],        # key:字符串;value:列表
    'k3': ('a', 'b', 'c'),  # key:字符串;value:元祖
    'k4': {                 # key:字符串;value:字典
        'name': 'demo',
        'age': '18'
    }
}

print(type(res),res)
运行结果: <class 'dict'> {}

print(type(res1),res1)
运行结果: <class 'dict'> {1: 2, 2: 'hello', ('k1',): 'v1', 'k2': [1, 2, 3], 'k3': ('a', 'b', 'c'), 'k4': {'name': 'demo', 'age': '18'}}

2.2 字典的索引

字典通过键值对中的键作为索引来获取对应的值。字典中的键是无序的。

res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
print(res1['k2']) #这种方式很好的将键和值联系起来,就像查字典一样。
运行结果: [1, 2, 3]

2.3 字典的常用操作

2.3.1 增加元素

字典可以直接利用 key 索引赋值的方式进行添加元素,如果 key 存在则修改字典;

1. 字典内增加键值对;
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
res1[10086] = 10086 # 字典内不存在键,所以添加键值对;
print(res1)
运行结果: {1: 2, 2: 'hello', ('k1',): 'v1', 'k2': [1, 2, 3], 'k3': ('a', 'b', 'c'), 'k4': {'name': 'demo', 'age': '18'}, 10086: 10086}

2. 字典内修改键值对;
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
res1[1] = 10000 # 字典内存在键,所以修改对应的值;
print(res1)
运行结果: {1: 10000, 2: 'hello', ('k1',): 'v1', 'k2': [1, 2, 3], 'k3': ('a', 'b', 'c'), 'k4': {'name': 'demo', 'age': '18'}}

3. 使用update{}扩展字典;
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
res2 = {'user': 'Python'}
res1.update(res2)
print(res1)
运行结果: {1: 2, 2: 'hello', ('k1',): 'v1', 'k2': [1, 2, 3], 'k3': ('a', 'b', 'c'), 'k4': {'name': 'demo', 'age': '18'}, 'user': 'Python'}

4. 使用update{}添加键值对;
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
res1.update({'user': 'Python'})
print(res1)
运行结果: {1: 2, 2: 'hello', ('k1',): 'v1', 'k2': [1, 2, 3], 'k3': ('a', 'b', 'c'), 'k4': {'name': 'demo', 'age': '18'}, 'user': 'Python'}

2.3.2 修改元素

直接通过 key 索引赋值的方式可以对字典进行修改,如果key不存在则添加;

res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
res1['k3'] = 'k3'
print(res1)
运行结果: {1: 2, 2: 'hello', ('k1',): 'v1', 'k2': [1, 2, 3], 'k3': 'k3', 'k4': {'name': 'demo', 'age': '18'}}

2.3.3 删除元素

删除字典提供了两个函数:pop、popitem

1. pop(key) 指定删除某个键,并返回该值
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
print(res1.pop(1))
运行结果: 2

2. popitem() 随机删除某个键值对,并返回二元元祖(key:value)
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
print(res1.popitem())
运行结果: ('k4', {'name': 'demo', 'age': '18'})

2.3.4 查询元素

通过 key 索引可以直接获取 key 对应的value,如果key不存在则抛出异常。

1. 通过 key 获取对应的value,不存在key就报错;
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
print(res1[1])
运行结果: 2

2. 通过 get 获取key对应的value,如果不存在返回None;
res1 = {
    1: 2,
    2: 'hello',
    ('k1',): 'v1',
    'k2': [1, 2, 3],
    'k3': ('a', 'b', 'c'),
    'k4': {
        'name': 'demo',
        'age': '18'
    }
}
print(res1.get('k2'))
运行结果: [1, 2, 3]
print(res1.get('user')) # 如果 key 不存在就返回None;
运行结果: None

6、其他类型

1. 布尔型

条件表达式的运算结果返回布尔型 bool,布尔型数据只有两个,True 和 False 表示

print(True) # 真
运行结果: True

print(False) # 假
运行结果: False

1.1 比较运算符

运算符描述
==等于-比较对象是否相等
is等于-比较对象的内存地址是否相同
!=不等于
>大于
<小于
>=大于等于
<=小于等于

 比较运算符运算后的结果是布尔型!

print(11 == 11)
运行结果: True

res = 11
print(res is 11)
运行结果: True

print(12 != 11)
运行结果: True

print(12 > 11)
运行结果: True

print(11 < 12)
运行结果: True

print(12 >= 11)
运行结果: True

print(11 <= 12)
运行结果: True

1.2 成员运算符

运算符描述实例
in如果在指定的序列中找到值返回True,否则FalseL = [1, 2, 3, 4, 5] a = 3 print(a in L) # True
not in如果在指定的序列中没有找到值返回True,否则Falseprint(a not in L) # False
1. in 
res = [1,3,4,5]
print(1 in res) # 1 在 res列表内。存在返回 True;
运行结果: True

print(6 in res) # 6 在 res列表内。不存在返回 False;
运行结果: False

2. not in
res = [1,3,4,5]
print(1 not in res) # 1 不在 res列表内,返回 False;
运行结果: False

print(6 not in res) # 6 不在 res列表内,返回 True;
运行结果: True

1.3 布尔型运算

布尔型数据可以和数值类型数据进行数学计算,这时 True 表示整数 1False表示整数 0;

print(True + 1)
运行结果: 2

print(False + 1)
运行结果: 1

1.4 布尔类型转换

任意数据都可以通过函数bool转换成布尔型。

None, 0(整数),0.0(浮点数),0.0+0.0j(复数),""(空字符串),空列表,空元组,空字典,空集合的布尔值都为False,其他数值为True

1. 返回 False
print(bool(0))
运行结果: False

print(bool(0.0))
运行结果: False

print(bool(0.0+0.0j))
运行结果: False

print(bool(''))
运行结果: False

print(bool([]))
运行结果: False

print(bool(()))
运行结果: False

print(bool({}))
运行结果: False

print(bool(set()))
运行结果: False

print(bool(None))
运行结果: False

2. 返回 True
print(bool(1))
运行结果: True

print(bool(2.4))
运行结果: True

print(bool(1.2+0.0j))
运行结果: True

print(bool('test'))
运行结果: True

print(bool(['test']))
运行结果: True

print(bool(('test')))
运行结果: True

print(bool({'test':'user'}))
运行结果: True

print(bool({'test'}))
运行结果: True

1.2 逻辑运算符

运算符描述
and与,如果x为False,x and y返回x的值,否则返回y的值
or或,如果x为True,x and y返回x的值,否则返回y的值
not非,如果x为True,返回False,反之,返回True

逻辑运算符两边的表达式不是布尔型时,在运算前会转换为布尔型;

1. and 简言之:一假则假,全真则真;
print(1 and True) # and方法优先计算左边的元素;
运行结果: True

2. or 简言之:一真则真,全假则假;
print(0 or False)
运行结果: True 

3. not 

2. None

None 是 Python 中的特殊数据类型,它的值就是它本身None,表示空,表示不存在。

print(None)
运行结果: None

7、可变与不可变对象

Python中的对象根据底层内存机制分为可变与不可变两种。

当一个可变类型的对象被赋值给另一个变量时,两个变量会指向同一个对象。

这意味着,如果修改其中一个变量所指向的对象,另一个变量也会受到影响。

而对于不可变类型的对象,则不会出现这种情况。

可变类型包括:列表 list、字典dict、集合set 。

这些类型的值可以被修改,即可以向其中添加、删除、修改元素等操作。

不可变类型包括:整数int、浮点数float、复数complex、布尔值bool、字符串str、元组tuple。

这些类型的值一旦创建,就不能被改变,任何对其值的修改都会创建一个新的对象。

8、可哈希对象

一个对象的哈希值如果在其生命周期内绝不改变,就被称为可哈希。

可哈希对象都可以通过内置函数 hash 进行求值。

不可变数据类型都是可哈希对象,可变数据类型都是不可哈希对象。

# 可哈希类型
print(hash(1))
运行结果: 1
 
print(hash(1.2))
运行结果: 461168601842738689
 
print(hash('test'))
运行结果: 6111045993774715694
 
print(hash('user',))
运行结果: 8166170637854711540
 
# 不可哈希类型
print(hash([1,2]))
运行结果: TypeError: unhashable type: 'list'
 
print(hash({'user':'test'}))
运行结果: TypeError: unhashable type: 'dict'
 
print(hash({'haha'}))
运行结果: TypeError: unhashable type: 'set'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值