>>>from collections import deque>>> queue =deque(["Eric", "John", "Michael"])>>> queue.append("Terry")# Terry arrives>>> queue.append("Graham")# Graham arrives>>> queue.popleft()# The first to arrive now leaves'Eric'>>> queue.popleft()# The second to arrive now leaves'John'>>> queue # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])
列表推导式
要创建列表,通常的做法是使用for循环,来遍历列表,并为其设置值:
>>> squares = []>>>for x inrange(10):... squares.append(x**2)...>>> squares[0,1,4,9,16,25,36,49,64,81]
或者我们可以使用列表推导式来更加简洁的生成列表:
squares = [x**2for x inrange(10)]
列表推导式的结构是由一对方括号所包含的以下内容:一个表达式,后面跟一个 for 子句,然后是零个或多个 for 或 if 子句。
列表推导式将会遍历for字句中的元素,并且使用表达式来求值,将生成的元素作为新的列表元素返回。
看一个复杂点的:
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y][(1,3), (1,4), (2,3), (2,1), (2,4), (3,1), (3,4)]
上面的表达式等价于:
>>> combs = []>>>for x in [1,2,3]:... for y in [3,1,4]:... if x != y:... combs.append((x, y))...>>> combs[(1,3), (1,4), (2,3), (2,1), (2,4), (3,1), (3,4)]
>>> a = [-1,1,66.25,333,333,1234.5]>>>del a[0]>>> a[1,66.25,333,333,1234.5]>>>del a[2:4]>>> a[1,66.25,1234.5]>>>del a[:]>>> a[]>>>del a
元组
元组跟列表很类似,不同的是元组是不可变的。
元组是以小括号来表示的,或者可以不使用括号。
>>> t =12345,54321,'hello!'>>> t[0]12345>>> t(12345,54321,'hello!')>>># Tuples may be nested:... u = t, (1,2,3,4,5)>>> u((12345,54321,'hello!'), (1,2,3,4,5))
>>> basket ={'apple','orange','apple','pear','orange','banana'}>>>print(basket)# show that duplicates have been removed{'orange','banana','pear','apple'}>>>'orange'in basket # fast membership testingTrue>>>'crabgrass'in basketFalse>>># Demonstrate set operations on unique letters from two words...>>> a =set('abracadabra')>>> b =set('alacazam')>>> a # unique letters in a{'a','r','b','c','d'}>>> a - b # letters in a but not in b{'r','d','b'}>>> a | b # letters in a or b or both{'a','c','r','d','b','m','z','l'}>>> a & b # letters in both a and b{'a','c'}>>> a ^ b # letters in a or b but not both{'r','d','b','m','z','l'}
和列表一样,集合也支持推导式:
>>> a ={x for x in'abracadabra'if x notin'abc'}>>> a{'r','d'}
>>> knights ={'gallahad':'the pure','robin':'the brave'}>>>for k, v in knights.items():... print(k, v)...gallahad the purerobin the brave
如果是列表,那么可以使用enumerate 函数来获取到index和value:
>>>for i, v inenumerate(['tic', 'tac', 'toe']):... print(i, v)...0 tic1 tac2 toe
之前我们还使用了zip函数,zip函数可以将多个序列中的元素一一匹配:
>>> questions = ['name','quest','favorite color']>>> answers = ['lancelot','the holy grail','blue']>>>for q, a inzip(questions, answers):... print('What is your {0}? It is {1}.'.format(q, a))...What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue.