python编程(3):数据结构

来源:互联网 发布:gamecenter数据不同步 编辑:程序博客网 时间:2024/05/22 17:02

1列表(List)

Python中列表是可变的,这是它区别于字符串和元组的最重要的特点,一句话概括即:列表可以修改,而字符串和元组不能


将列表当做堆栈使用

stack=[3,4,5]stack.append(6)stack.append(7)print(stack)  #3,4,5,6,7print(stack.pop()) #7print(stack)       #3,4,5,6print(stack.pop()) #6print(stack)       #3,4,5

将列表当作队列使用

from collections import dequequeue = deque(["Eric","John","Micheal"])queue.append("Terry")queue.append("Graham")print(queue)print(queue.popleft())print(queue)print(queue.popleft())print(queue)

https://docs.python.org/3/library/stdtypes.html#list  list ndefinition
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists  class list api


2元组(Tuple)

#元组和序列t = 12345,54321,'hello!'print(t[0]) #12345print(t)    #(12345, 54321, 'hello!')u = t,(1,2,3,4,5)  #((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))print(u)

https://docs.python.org/3/library/stdtypes.html#tuples


3集合(Set)

集合是一个无序不重复元素的集,基本功能包括关系测试和消除重复元素

创建一个空集合,你必须用set()而不是{},后者创建一个空的字典

basket = {'apple','orange','apple','pear','orange','banana'}print(basket)  # show that duplicates have been removedprint('orange' in basket)print('hello' in basket)a = set("abracadabra")b = set("alacazam")print(a)  #unique letter in aprint(b)  #unique letter in bprint(a-b) #letters in a not in bprint(a | b ) # letters in  a or bprint(a & b)  # letters in a and bprint(a ^ b)  # letters in  a or b but not bothprint('K' in a ) # whether 'K' in  a setprint({x for x in 'abracadabra' if x not in 'abc'}) #集合也支持推导式
https://docs.python.org/3/tutorial/datastructures.html#sets

4词典(Dictionary)

序列是以连续的整数为索引,与此不同的是,字典以关键字为索引,关键字可以是任意不可变类型,通常用字符串或数值。
理解字典的最佳方式是把它看做无序的键=>值对集合。在同一个字典之内,关键字必须是互不相同。
一对大括号创建一个空的字典:{}

tel = {'jack':4098,'sape':4139}tel['guido']=4127print(tel)print(tel['jack'])del tel['sape']print(tel)print(list(tel.keys()))print(sorted(tel.keys()))print('jack' in tel)print('guido' not in tel)

https://docs.python.org/3/tutorial/datastructures.html#dictionaries


参考链接

https://docs.python.org/3/tutorial/datastructures.html#data-structures

0 0