python3数据类型及操作
Number
counter = 100 # 整型变量
miles = 1000.0 # 浮点型变量
num_complex = complex(1.5, 2.5)
print(counter) # 100
print(miles) # 1000.0
print(num_complex) # (1.5+2.5j)
# 数字类型转换
print(float(counter)) # 100.0
print(int(miles)) # 1000
print(complex(counter)) # (100+0j)
print(complex(counter, miles)) # (100+1000j)
print(5 + 4) # 加法 输出 9
print(4.3 - 2) # 减法 输出 2.3
print(3 * 7) # 乘法 输出 21
print(2 / 4) # 除法,得到一个浮点数 输出 0.5
print(2 // 4) # 除法,得到一个整数 输出 0
print(17 % 3) # 取余 输出 2
print(2**5) # 乘方 输出 32
String
创建字符串可以使用单引号、双引号、三单引号和三双引号,其中三引号可以多行定义字符串
# String(字符串) 创建字符串可以使用单引号、双引号、三单引号和三双引号,其中三引号可以多行定义字符串
str = "Python学习"
print(len(str)) # 8
# 成员运算
print("Python" in str) # True
print("Python" not in str) # False
# 切片
print(str[0], str[-1], str[3:], str[::-1], str[::-2]) # 'P', '习', 'hon学习', '习学nohtyP', '习nhy'
# 查找
print(str.count("P")) # 1 返回子串在str中出现的次数
print(str.find("P")) # 0, 返回第一次出现的子串的下标
print(str.rfind("P")) # 0, 返回最后一次出现的子串的下标
print(str.find("我")) # -1, 查找不到返回-1
print(str.find("h", 2)) # 3, 设定下标2开始查找
print(str.index("y")) # 1, 返回第一次出现的子串的下标
print(str.rindex("y")) # 1, 返回最后一次出现的子串的下标
try:
print(str.index("我")) # 查找不到会抛出异常
except ValueError:
print("'{}'字符串中没有'{}'".format(str, "我"))
# 替换,还可以使用正则表达式替换
print(str.replace("th", "zh"))
print(str.replace("th", "zh", 1)) # 指定替换次数
# 转大小写
print(str.upper()) # 'PYTHON学习'
print(str.lower()) # 'python学习'
print(str.swapcase()) # 'pYTHON学习', 大小写互换
print("good".capitalize()) # 'Good', 首字母大写,其它字母小写
print("a good day".title()) # 'A Good Day', 每个词(以空格分隔)的首字母大写
# 判断
print(str.istitle()) # True,如果所有的词的首字母都是大写返回True
print(str.isupper()) # False,如果所有的字符都是大写字母返回True
print(str.islower()) # False,如果所有的字符都是小写字母返回True
print("abc123".isalnum()) # True, 如果所有的字符都是字母或数字返回True
print("and".isalpha()) # True,如果所有的字符都是字母返回True
print("123".isdigit()) # True,如果所有的字符都是数字返回True
print(" ".isspace()) # True,如果所有的字符都是空格返回True
print(str.startswith("He")) # False
print(str.endswith("!")) # True
str1 = " Python 学习 "
# 去空格与补齐
print("'{}'".format(str1.strip())) # 'Python 学习' 去除字符串两边的空格
print("'{}'".format(str1.lstrip())) # 'Python 学习 ' 去除字符串左边的空格
print("'{}'".format(str1.rstrip())) # ' Python 学习' 去除字符串右边的空格
print("'{}'".format(str.center(10))) # ' Python学习 ' 返回长度为width的字符串,在原字符串的两边补空格
print("'{}'".format(str.ljust(10))) # 'Python学习 ' 返回长度为width的字符串,在原字符串的右边补空格
print("'{}'".format(str.rjust(10))) # ' Python学习' 返回长度为width的字符串,在原字符串的左边补空格
# 格式化
print("'%s, %s'" % ("lily", 3)) # 'lily, 3'
print("'{}, {}'".format("lily", 3)) # 'lily, 3'
print("'{0}, {1}, {0}'".format("lily", 3)) # 'lily, 3, lily'
print("'{name}: {age}'".format(age=3, name="lily")) # 'lily: 3'
print("PI: {0:.3f}".format(math.pi)) # PI: 3.142
print("'{0:10} ==> {1:10d}'".format("lily", 123)) #'lily ==> 123'
print("name: {0[name]:s}".format({"name": "lily"})) # name: lily
a = 321
b = 123
print(f"{a} * {b} = {a * b}")
# 连接与分割
print("hello" + " world") # hello world
list = ["2023", "09", "09", "22:00"]
str = "-".join(list)
print(str) # '2023-09-09-22:00'
print(str.split("-")) # ['2023', '09', '09', '22:00']
print(str.rsplit("-", 1)) # ['2023-09-09', '22:00']
# encode 将字符转换为字节
str = "学习Python"
print(str.encode()) # 默认编码是 UTF-8 输出:b'\xe5\xad\xa6\xe4\xb9\xa0Python'
print(str.encode("gbk")) # 输出 b'\xd1\xa7\xcf\xb0Python'
# decode 将字节转换为字符
print(str.encode().decode("utf8")) # 输出 '学习Python'
print(str.encode("gbk").decode("gbk")) # 输出 '学习Python'
字符串前缀
r 前缀代表原始字符串
原始字符串会禁用转义字符的处理,字符串中的反斜杠 \ 不会被解释为转义序列。
常用于处理包含反斜杠的文件路径或正则表达式等情况,以避免转义字符的干扰。
f 前缀代表格式化字符串。
格式化字符串允许在字符串中插入变量或表达式的值,使用大括号 {} 包裹变量或表达式。
常用于创建动态字符串,特别是需要插入变量或表达式的情况。
u 前缀代表 Unicode 字符串
在 Python 2.x 中,u 前缀用于表示 Unicode 字符串。
在 Python 3.x 中,所有字符串都默认是 Unicode 字符串,因此通常不再需要显式使用 u。
b 前缀代表 Bytes 类型字符串
在 python3 中 str 和 bytes 转化:str.encode('utf-8') bytes.decode('utf-8')
List
nl = [1, 2, 0, 3, 5]
# 取值
print(nl[2], nl[-2], nl[3:], nl[::-1]) # 0 3 [3, 5] [5, 3, 0, 2, 1]
# 赋值
nl[0] = 1
# 序列中包含元素的个数
print(len(nl)) # 5
# 判断
print(all(nl)) # False 所有元素都为True的话返回True
print(any(nl)) # True 任一元素为True的话返回True
print(10 in nl) # False 判断元素是否在列表中
# 统计
print(sum(nl)) # 11 序列中所有元素的和
print(min(nl)) # 0 序列中最小的元素
print(max(nl)) # 5 序列中最大的元素
# 查找
print(nl.count(5)) # 1 计数,看总共有多少个5
print(nl.count(10)) # 0 计数,看总共有多少个10
print(nl.index(3)) # 3 查询 nl 的第一个3的下标
# print(nl.index(10)) # 查找一个不存在列表中的元素ValueError
# 添加
nl.append(6) # 在 nl 的最后增添一个新元素6
nl.insert(0, 9) # 在下标为0的位置插入9
nl.extend([7, 8])
print(nl) # [9, 1, 2, 0, 3, 5, 6, 7, 8]
# 排序
nl.sort()
print(nl) # [0, 1, 2, 3, 5, 6, 7, 8, 9]
nl.reverse()
print(nl) # [9, 8, 7, 6, 5, 3, 2, 1, 0]
# 删除
print(nl.pop()) # 0 从nl中去除最后一个元素,并将该元素返回
print(nl) # [9, 8, 7, 6, 5, 3, 2, 1]
nl.remove(2) # 从nl中去除第一个2
print(nl) # [9, 8, 7, 6, 5, 3, 1]
# nl.remove(10) # 删除一个不存在列表中的元素ValueError
del nl[0] # 删除元素
print(nl) # [8, 7, 6, 5, 3, 1]
# 遍历
for val in nl:
print(val)
# 复制列表
nl_new = nl.copy()
print(nl) # [8, 7, 6, 5, 3, 1]
# 序列相加
print(nl + nl_new) # [8, 7, 6, 5, 3, 1, 8, 7, 6, 5, 3, 1]
print(nl * 2) # [8, 7, 6, 5, 3, 1, 8, 7, 6, 5, 3, 1]
# 转换为列表
print(list("python")) # ['p', 'y', 't', 'h', 'o', 'n']
print(list(("a", "b", "c", "d"))) # ['a', 'b', 'c', 'd']
# 分片赋值
name = list("Pyther")
name[4:] = "on"
print(name) # ['P', 'y', 't', 'h', 'o', 'n']
name[1:] = list("erl")
print(name) # ['P', 'e', 'r', 'l']
Tuple
元组的元素不能修改
tl = ("a", "b", "c", "d")
print(tl[0]) # a
print(tl[0:3]) # ('a', 'b', 'c')
print(tl[::2]) # ('a', 'c')
print(tl[::-2]) # ('d', 'b')
# 打包操作
a = 1, 10, 100
print(type(a)) # <class 'tuple'>
print(a) # (1, 10, 100)
# 解包操作
i, j, k = a
print(i, j, k) # 1 10 100
a = 1, 10, 100, 1000
i, j, *k = a
print(i, j, k) # 1 10 [100, 1000]
i, *j, k = a
print(i, j, k) # 1 [10, 100] 1000
*i, j, k = a
print(i, j, k) # [1, 10] 100 1000
# 交换变量的值
a, b = i, a
# 元组中包含元素的个数
print(len(tl)) # 4
# 判断
print(all(tl)) # True 所有元素都为True的话返回True
print(any(tl)) # True 任一元素为True的话返回True
print("e" in tl) # False 判断元素是否在元组中
# 查找
print(tl.count("b")) # 1 计数,看总共有多少个b
print(tl.index("b")) # 1 查询 nl 的第一个b的下标
tl1 = (1, 2, 0, 3, 5)
# 统计
print(sum(tl1)) # 11 元组中所有元素的和
print(min(tl1)) # 0 元组中最小的元素
print(max(tl1)) # 5 元组中最大的元素
# 遍历
for val in tl:
print(val)
# 序列相加
print(tl + tl1) # ('a', 'b', 'c', 'd', 1, 2, 0, 3, 5)
print(tl * 2) # ('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd')
# 转换为元组
print(tuple(nl)) # (8, 7, 6, 5, 3, 1)
print(tuple("python")) # ('p', 'y', 't', 'h', 'o', 'n')
Sets
无序不重复元素的序列,不能被切片也不能被索引
# Sets(集合) 无序不重复元素的序列,不能被切片也不能被索引
st = {1, 0, 3, 4}
# 集合中包含元素的个数
print(len(st)) # 4
# 添加
st.add(2)
print(st) # {0, 1, 2, 3, 4}
# 删除
st.discard(5)
print(st) # {0, 1, 2, 3, 4}
st.discard(2)
print(st) # {0, 1, 3, 4}
print(st.pop()) # 0
print(st) # {1, 3, 4}
st.remove(3)
print(st) # {1, 4}
# 清空元素
# st.clear()
# 统计
print(sum(st)) # 8 集合中所有元素的和
print(min(st)) # 0 集合中最小的元素
print(max(st)) # 4 集合中最大的元素
# 判断
print(all(st)) # False 所有元素都为True的话返回True
print(any(st)) # True 任一元素为True的话返回True
print(6 in st) # False 判断元素是否在集合中
# 遍历
for val in st:
print(val)
# 空集合
st = set()
print(len(st)) # 0
set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {2, 4, 6, 8, 10}
# 交集
print(set1 & set2) # {2, 4, 6}
print(set1.intersection(set2)) # {2, 4, 6}
# 并集
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 10}
print(set1.union(set2)) # {1, 2, 3, 4, 5, 6, 7, 8, 10}
# 差集
print(set1 - set2) # {1, 3, 5, 7}
print(set1.difference(set2)) # {1, 3, 5, 7}
# 对称差
print(set1 ^ set2) # {1, 3, 5, 7, 8, 10}
print(set1.symmetric_difference(set2)) # {1, 3, 5, 7, 8, 10}
# 判断set1是不是set2的子集
print(set1.issubset(set2)) # False
# set2是不是set1的超集
print(set2.issuperset(set1)) # False
# 判断两个集合有没有相同的元素,如果没有相同元素,该方法返回True
print(set1.isdisjoint(set2)) # False
# 不可变集合
# 不能添加和删除元素,frozenset在其他方面跟set是一样的
fset1 = frozenset({1, 3, 5, 7})
fset2 = frozenset(range(1, 6))
Dictionary
字典是一种映射类型-键值对,字典的键必须为不可变类型,且不能重复
# Dictionary(字典) 字典是一种映射类型-键值对,字典的键必须为不可变类型,且不能重复
dic = {}
dic = dict(name="aa", age=11, height=150)
dic = {"tom": 11, "sam": 57, "lily": 100}
# 可以通过Python内置函数zip压缩两个序列并创建字典
items1 = dict(zip("ABCDE", "12345"))
print(items1) # {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5'}
items2 = dict(zip("ABCDE", range(1, 10)))
print(items2) # {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
# 用字典生成式语法创建字典
items3 = {x: x**3 for x in range(1, 6)}
# 查询词典中的元素总数
print(len(dic)) # 3
# 检查键是否存在
print("tom" in dic) # True
# 取值
print(dic["tom"]) # 11
print(dic.get("tom")) # 11
print(dic.get("rose", 45)) # 45
print(dic.keys()) # dict_values([11, 57, 100]) 返回dic所有的键
print(dic.values()) # dict_values([11, 57, 100]) 返回dic所有的值
print(dic.items()) # dict_items([('tom', 11), ('sam', 57), ('lily', 100)]) 返回dic所有的元素(键值对)
for key, value in dic.items():
print(f"{key}:\t{value}")
# 赋值
dic["tom"] = 30
dic["lilei"] = 99
dic.setdefault("jane", 40)
# 合并
dic.update({"jack": 90})
print(dic) # {'tom': 30, 'sam': 57, 'lily': 100, 'lilei': 99, 'jane': 40, 'jack': 90}
# 遍历
for key in dic:
print(f"{key}:\t{dic[key]}")
# 浅拷贝: 引用对象 赋值
dict2 = dic
# 拷贝
dict3 = dic.copy()
# 删除
print(dic.popitem()) # ('jack', 90)
print(dic.pop("lilei")) # 99
del dic["tom"] # 删除 dic 的 tom 元素
print(dic) # {'sam': 57, 'lily': 100, 'jane': 40}
dic.clear() # 清空dic,dict变为{}
print(dic) # {}
seq = ("name", "age", "class")
dic = dict.fromkeys(seq)
print(dic) # {'name': None, 'age': None, 'class': None}
dic = dict.fromkeys(seq, 10)
print(dic) # {'name': 10, 'age': 10, 'class': 10}
浙公网安备 33010602011771号