目录
- 列表、元组操作
- 字符串操作
- 字典操作
- 集合操作
- 文件操作
- 字符编码与转码
1.列表、元组操作
列表是最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作
定义列表
names = ["张三","李四","王麻子"]
通过下标取列表中的数据.下标按0开始计算
names = ["张三","李四","王麻子"] print(names[0]) 张三 print(names[1]) 李四 print(names[2]) 王麻子 注意:也可以倒着取 print(names[-3]) 张三 print(names[-2]) 李四 print(names[-1]) 王麻子
切片:取多个元素(顾头不顾尾.不取尾)
names = ["张三","李四","王麻子","疯子","傻子"] print(names[0:2]) [‘张三‘, ‘李四‘] print(names[:3]) [‘张三‘, ‘李四‘, ‘王麻子‘] print(names[1:]) [‘李四‘, ‘王麻子‘, ‘疯子‘, ‘傻子‘] print(names[0::2]) [‘张三‘, ‘王麻子‘, ‘傻子‘] print(names[::2]) [‘张三‘, ‘王麻子‘, ‘傻子‘]
追加(在最后一位增加)
names = ["张三","李四","王麻子","疯子","傻子"] names.append("SB") print(names)[‘张三‘, ‘李四‘, ‘王麻子‘, ‘疯子‘, ‘傻子‘, ‘SB‘]
插入(随便在什么地方插入)
names = ["张三","李四","王麻子","疯子","傻子"] names.insert(2,"老寒腿") names.insert(5,"大脚") print(names) [‘张三‘, ‘李四‘, ‘老寒腿‘, ‘王麻子‘, ‘疯子‘, ‘大脚‘, ‘傻子‘, ‘SB‘]
修改
names = ["张三","李四","王麻子","疯子","傻子"] names[2] = ("麻子") print(names) [‘张三‘, ‘李四‘, ‘麻子‘, ‘疯子‘, ‘傻子‘]
删除
#指定删除下标对应的 names = ["张三","李四","王麻子","疯子","傻子"] del names[4] print(names) [‘张三‘, ‘李四‘, ‘王麻子‘, ‘疯子‘] #使用remove删除时只能删除第一个出现的 names = ["张三","李四","李四","王麻子","疯子","傻子"] names.remove("李四") print(names) [‘张三‘, ‘李四‘, ‘王麻子‘, ‘疯子‘, ‘傻子‘] #使用pop删除时删除列表中的最后一个值 names = ["张三","李四","李四","王麻子","疯子","傻子"] names.pop() print(names) [‘张三‘, ‘李四‘, ‘李四‘, ‘王麻子‘, ‘疯子‘]
拷贝
names = ["张三","李四","李四","王麻子","疯子","傻子"] names_copy = names.copy() print(names_copy) [‘张三‘, ‘李四‘, ‘李四‘, ‘王麻子‘, ‘疯子‘, ‘傻子‘]
统计
names = ["张三","李四","李四","王麻子","疯子","傻子"] print("李四出现次数:",names.count("李四")) 李四出现次数: 2
排序
names = ["张三","李四","李四","王麻子","疯子","傻子","3","2"] names.sort() print(names) [‘2‘, ‘3‘, ‘傻子‘, ‘张三‘, ‘李四‘, ‘李四‘, ‘王麻子‘, ‘疯子‘]
#3.0里不同数据类型不能放在一起排序了
获取下标
names = ["张三","李四","李四","王麻子","疯子","傻子","1","3","2"] print("李四的下标是:",names.index("李四")) 李四的下标是: 1 #只返回找到的第一个下标
时间: 2024-11-03 05:42:12