Python 基本数据结构:list、tuple、dict、set
基本数据结构常用函数
List
1. append和 extend
list.append(a) 意为将 a 作为整体加入list
lst = [1,2,3,4,5]
lst.append([,2,3])
print (lst)
# 输出:[1, 2, 3, 4, 5, [1, 2, 3]]
list.extend(a) 若a 为可迭代对象,将a内部元素加入list
lst = [1,2,3,4,5]
lst.extend([1,2,3])
print (lst)
# 输出:[1, 2, 3, 4, 5, 1, 2, 3]
2. insert和pop
在指定位置插入元素或者删除元素(二者互为逆运算)
lst = [1,2,3,4,5]
lst.insert(len(lst), 100)
print (lst)
# 输出:[1, 2, 3, 4, 5, 100]
lst.pop(len(lst) - 1)
print (lst)
# 输出:[1, 2, 3, 4, 5]
3. remove
删除遇到的第一个元素(从左到右)
lst = [1,2,5,3,4,5]
lst.remove(5)
print (lst)
# 输出:[1, 2, 3, 4, 5]
4. in
判断是否存在某元素
lst = [1,2,3,4,5]
if 5 in lst:
print ("yes")
else:
print ("no")
# 输出:yes
5. sort(key)
按照某种方式排序
def fun(ele):
return ele[0]
lst = [(5,6),(7,8),(1,2),(3,4)]
lst.sort(key=fun)
print (lst)
# 输出:[(1, 2), (3, 4), (5, 6), (7, 8)]
Dict
1. dict(iterable)
将可迭代数据转为dict
lst = [(5,6),(7,8),(1,2),(3,4)]
d = dict(lst)
print (d)
# 输出:{5: 6, 7: 8, 1: 2, 3: 4}
2. in
判断key是否存在
d = {1: 2, 3: 4, 5: 6, 7: 8}
if 3 in d:
print ("we have 3")
if 2 in d:
print ("we have 2")
# 输出:we have 3
3. update
合并dict,如有重复的键,用后面的替代前面的
d1 = {1: 2, 3: 4, 5: 6, 7: 8}
d2 = {5:12, 7:56}
d1.update(d2)
print (d1)
# 输出:1: 2, 3: 4, 5: 12, 7: 56}
4. dict键的限制
dict的key只能使用不可变对象(immutable),所以像list和dict本身是不可以作为键的。如果要使用list作为键,可以先将list转化为tuple
Set
1. 转化list为set
s1 = [1,2,3,4,5]
print (set(s1))
# 输出:{1, 2, 3, 4, 5}
2. 集合运算
集合运算包括并,交,差,对称差(去掉两个集合共有的部分)。
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
print (s1 | s2)
print (s1 & s2)
print (s1 - s2)
print (s1^s2)
# 输出:
# {1, 2, 3, 4, 5, 6, 7, 8}
# {4, 5}
# {1, 2, 3}
# {1, 2, 3, 6, 7, 8}
3. 判断是否为子集或父集合
s1 = {1,2,3,4,5}
s2 = {4,5}
s3 = {4,5,6,7,8}
print (s1.issuperset(s2))
print (s1.issuperset(s3))
# 输出:
# True
# False
Tuple
元组作为不可变对象,相对简单,在此不做介绍
参考文献:
[1] python数据结构