python-基础 列表 集合 字典

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-基础 列表 集合 字典相关的知识,希望对你有一定的参考价值。

目录

  1. 列表、元组操作
  2. 字符串操作
  3. 字典操作
  4. 集合操作
  5. 文件操作
  6. 字符编码与转码

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    
#只返回找到的第一个下标

  

  

 



以上是关于python-基础 列表 集合 字典的主要内容,如果未能解决你的问题,请参考以下文章

Python基础2 列表字典集合

python-基础 列表 集合 字典 文件处理

python基础之列表,字典,集合

python基础一 -------如何在列表字典集合中根据条件筛选数据

python基础--列表元祖字典集合

python基础-列表 元组 集合 字典区别和用法