python中数据类型
第一类:不可变类型、静态数据类型、不支持增删改操作
数字(number)
字符串(string)
元组(tuple)
布尔类型(bool)
第二类:可变类型、动态数据类型、支持增删改操作
列表(list)
字典(dictionary)
集合(set)
python基本数据类型 –元组
1、元组的定义
元组是python的内置数据类型之一,是一个不可变序列。元素不支持增、删、改操作
2、元组的使用
"""
1、元组创建 使用小括号()
"""
t = ("你好", "我好", "大家好")
print(t)
print(type(t))
print(t[2])
print(t[:2])
# 不能修改 -- 报错
t[1] = "呵呵"
# 只包含一个元组的元素需要使用逗号和小括号
t = (1, )
print(t)
print(type(t))
# 元组的遍历
t = (11,22,33)
for i in t:
print(i)
# 元组的添加
t = ("呵呵", 123, [], "可乐")
print(t)
t[2].append("西瓜")
print(t)
python基本数据类型 –列表
1、列表的介绍
列表是python的内置数据类型之一,是一个可变序列。列表支持增、删、改操作:
特点如下:
有序集合:元素按照插入顺序存储
可变类型:创建后可以修改(增删改)
异构存储:可以存储不同类型的数据
动态大小:可以随时扩展或收缩
支持索引和切片:像字符串一样可以通过下标访问
2、列表的使用
# 空列表
empty_list = []
empty_list = list()
# 包含元素的列表
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'a', 3.14, True]
nested = [[1, 2], [3, 4]] # 嵌套列表
# 使用list()构造函数
from_string = list('hello') # ['h', 'e', 'l', 'l', 'o']
from_tuple = list((1, 2, 3)) # [1, 2, 3]
# 列表的索引
fruits = ['apple', 'banana', 'cherry', 'date']
# 正向索引(从0开始)
print(fruits[0]) # 'apple'
print(fruits[2]) # 'cherry'
# 负向索引(从-1开始)
print(fruits[-1]) # 'date'
print(fruits[-2]) # 'cherry'
# 切片操作 切片之后得到的还是一个列表
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['cherry', 'date']
print(fruits[::-1]) # 反转列表 ['date', 'cherry', 'banana', 'apple']
# 列表元素的修改(这就是列表与元素的区别)
colors = ['red', 'green', 'blue']
# 修改元素
colors[1] = 'yellow' # ['red', 'yellow', 'blue']
# 添加元素
colors.append('purple') # 末尾添加
colors.insert(1, 'orange') # 指定位置插入
# 删除元素
del colors[0] # 删除指定位置
colors.remove('blue') # 删除指定值
popped = colors.pop() # 删除并返回最后一个元素
colors.pop(1) # 删除并返回指定位置元素
# 清空列表
colors.clear()
# 列表中常用的方法如下(内置方法)
nums = [1, 2, 3, 4, 5]
# 添加元素
nums.append(6) # [1, 2, 3, 4, 5, 6]
nums.extend([7, 8]) # [1, 2, 3, 4, 5, 6, 7, 8]
nums.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
# 删除元素
nums.remove(3) # 删除第一个3
nums.pop() # 删除并返回最后一个元素
nums.clear() # 清空列表
# 查找和统计
index = nums.index(4) # 返回第一个4的索引
count = nums.count(2) # 统计2出现的次数
# 排序和反转
nums.sort() # 升序排序
nums.sort(reverse=True) # 降序排序
nums.reverse() # 反转列表
sorted_nums = sorted(nums) # 返回新排序列表,不改变原列表
# 复制列表
copy_nums = nums.copy()
copy_nums = nums[:] # 切片复制
# 列表的一些操作
a = [1, 2, 3]
b = [4, 5, 6]
# 合并列表
combined = a + b # [1, 2, 3, 4, 5, 6]
a.extend(b) # a变为[1, 2, 3, 4, 5, 6]
# 重复列表
repeated = a * 2 # [1, 2, 3, 1, 2, 3]
# 成员检查
print(3 in a) # True
print(7 not in a) # True
# 列表长度
length = len(a) # 6
# 遍历列表
for item in a:
print(item)
# 带索引遍历
for index, value in enumerate(a):
print(index, value)