python六种数据结构:
数值(number)、字符串(string)、列表(list)、元祖(tuple)、字典(dictionary)、集合(set)
1列表
特点:有序可变,支持增删改查
定义一个空列表a=[] a=list()
列表增(3种)
append (a.append("ad"))
insert (a.insert(0,100))
extend (a.extend(b))
列表删(4种)
remove (a.remove(值))
pop (a.pop(0),不是del)
del (del a[0,2]) 注意和pop用法区分
clear (a.clear(),是内置方法,需要加括号)
列表改(1种)
a[0]=5
列表查(1种)
列表名[start:end:step] (a[:5])
列表常用方法:
list.reverse()
list.index(元素值)
list.count(元素值)
list.sort(reverse=True) 未指定时默认升序排列,排序后如需打印,直接打印list 本身即可
2元祖
特点:有序不可变,不能修改,支持查
定义一个空元祖a=() a=tuple()
元祖查(1种)
元祖名[start:end:step]
元祖操作(2种)
*和+
元祖常用方法:
tuple.index(元素值)
tuple.count(元素值)
3字典
特点:无序可变键值对,支持增删改查
新建空字典 a={} a=dict()
字典新增(2种)
update (a.update({“a”:1,“b”:2}))
a[“b”]=4
字典删除(4种)
popitem (默认删除字典最后一个元素) 注意无remove
pop (a.pop(key))
del (del a[key])
clear (a.clear())
字典改(1种)
a[key]=新value
字典查(1种)
a[key]
字典常用方法:
dict.keys()
dict.values()
dict.items()
dict.copy() 复制字典,生成一个新字典
dict.get(key,default)
4集合
特点:无序可变,支持增删
新建空集合
a=set()
新建非空集合
a={"a",1,2,3,4}
集合增(2种)
add (a.add("adbs")) 只能跟字符串和数字
update (a.update("dfd"))
集合删(4种)
pop (a.pop(),随机删除)
remove (a.remove(值),如果元素不存在,则会报错)
discard (a.discard(值),如果元素不存在,不会报错)
clear (a.clear())
集合运算:交集,并集、差集
set1.intersection(set2)
set1.uniton(set2)
set1.difference(set2)