Container analysis
classification
The container here refers to several types of containers officially provided by python
list: list
set: set
tuple: tuple
dict: dictionary
1. List
ls = []
ls = list()
Access elements
through subscripts Traverse (access elements one by one)
common linear lists: stack, queue, array, list
列表的常见方法
append(元素) # 在列表尾部追加一个元素
insert(索引位置,元素) # 在特定的位置添加元素
clear() # 清除列表
count(element) # 统计元素出现的个数
index(element) # 查询元素首次出现索引(如果这个列表有很多重复的,找到第一个的位置就不再找了),如果不存在会抛出异常
remove(element) # 通过元素移除对应的元素
pop([index]) # 默认删除最后一个元素,如果指定了位置,则删除对应位置的元素
reverse() # 翻转列表顺序
copy() # 浅拷贝对象(堆对象的复制)
extend(可迭代对象) # 合并列表
sort() # 排序(有字母的话,看首字母的ASCII值,值大的排后面)
Multidimensional list
[[],[],[],[],[]]
2. Collection
Features: Disordered, elements cannot be repeated
1. How to define set collection
s = {
元素1, 元素2...}
s = set()
s = set({
元素1, 元素2...})
s = set([元素1, 元素2...]) # 将list转换为set对象
ls = list({
元素1, 元素2...}) # 将set转换为list对象
2. Operate through official methods
add(元素) 随机添加
clear 清除
copy 浅拷贝
remove 通过元素本身移除,如果元素存在就抛出异常
discard(元素) 移除特定元素,如果元素不存在,就什么都不做
pop() 随机移除元素
intersection 交集
union 并集
difference 差集
update 合并集合
set—————————————不能存储重复数据
3. Tuples
Features: immutable data type, it is not allowed to be modified or changed
the definition of tuple:
t = () 定义元组,但是不推荐这么使用,因为元组不可变
t = (“春”,“夏”,“秋”,“冬”) 建议定义时初始值化
t = tuple(())
注意:三种容器都可以使用对应的函数完成转换
Common method:
count count the number of elements
index query the index where the element is located
4. Dictionary
key:Value one
-to- one mapping is a kind of key-value key-value pair structure to store data in
python, the key cannot be repeated, otherwise it will overwrite the data and the
value type is arbitrary
How to access the values of the dictionary:
Use the key in the dictionary to get the value corresponding to the key
d["name"] Get the value corresponding to the name, if the key does not exist, throw an exception
d.get("age") You can also use the get method, if the key does not exist, Returns None
Common ways to use dictionaries
clear 清除
copy 浅拷贝
fromkeys() 将其他可迭代对象转换为字典
get
items() 迭代出每一个键值对[(),()]
keys()
value()
setdefault 新增key和value
update
pop(key) 通过key删除key对应的键值对,如果不存在就报错
popitem 对按后进先出的顺序返回