每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。如果希望表达式推导出一个元组,就必须使用括号。
这里我们将列表中每个数值乘三,获得一个新的列表:
>>> vec =[2,4,6] >>>[3*x for x in vec] [6,12,18]
现在我们玩一点小花样:
>>>[[x, x**2]for x in vec] [[2,4],[4,16],[6,36]]
这里我们对序列里每一个元素逐个调用某方法:
>>> freshfruit =[' banana',' loganberry ','passion fruit '] >>>[weapon.strip()for weapon in freshfruit] ['banana','loganberry','passion fruit']
我们可以用 if 子句作为过滤器:
>>>[3*x for x in vec if x >3] [12,18] >>>[3*x for x in vec if x <2] []
以下是一些关于循环和其它技巧的演示:
>>> vec1 =[2,4,6] >>> vec2 =[4,3, -9] >>>[x*y for x in vec1 for y in vec2] [8,6, -18,16,12, -36,24,18, -54] >>>[x+y for x in vec1 for y in vec2] [6,5, -7,8,7, -5,10,9, -3] >>>[vec1[i]*vec2[i]for i inrange(len(vec1))] [8,12, -54]
列表推导式可以使用复杂表达式或嵌套函数:
>>>[str(round(355/113, i))for i inrange(1,6)] ['3.1','3.14','3.142','3.1416','3.14159']
>>>[[row[i]for row in matrix]for i inrange(4)] [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
以上实例也可以使用以下方法来实现:
>>> transposed =[] >>>for i inrange(4):
... transposed.append([row[i]for row in matrix])
... >>> transposed [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
另外一种实现方法:
>>> transposed =[] >>>for i inrange(4):
... # the following 3 lines implement the nested listcomp
... transposed_row=[]
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
... >>> transposed [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
del 语句
使用 del 语句可以从一个列表中根据索引来删除一个元素,而不是值来删除元素。这与使用 pop() 返回一个值不同。可以用 del 语句从列表中删除一个切割,或清空整个列表(我们以前介绍的方法是给该切割赋一个空列表)。例如:
>>> 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 删除实体变量:
>>>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))
>>># 以下演示了两个集合的操作
... >>> a =set('abracadabra') >>> b =set('alacazam') >>> a # a 中唯一的字母 {'a','r','b','c','d'} >>> a - b # 在 a 中的字母,但不在 b 中 {'r','d','b'} >>> a | b # 在 a 或 b 中的字母 {'a','c','r','d','b','m','z','l'} >>> a & b # 在 a 和 b 中都有的字母 {'a','c'} >>> a ^ b # 在 a 或 b 中的字母,但不同时在 a 和 b 中 {'r','d','b','m','z','l'}
>>># 以下演示了两个集合的操作
... >>> a =set('abracadabra') >>> b =set('alacazam') >>> a # a 中唯一的字母 {'a','r','b','c','d'} >>> a - b # 在 a 中的字母,但不在 b 中 {'r','d','b'} >>> a | b # 在 a 或 b 中的字母 {'a','c','r','d','b','m','z','l'} >>> a & b # 在 a 和 b 中都有的字母 {'a','c'} >>> a ^ b # 在 a 或 b 中的字母,但不同时在 a 和 b 中 {'r','d','b','m','z','l'}
>>> knights ={'gallahad': 'the pure','robin': 'the brave'} >>>for k, v in knights.items():
... print(k, v)
... gallahad the pure
robin the brave
在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到:
>>> knights ={'gallahad': 'the pure','robin': 'the brave'} >>>for k, v in knights.items():
... print(k, v)
... gallahad the pure
robin the brave
同时遍历两个或更多的序列,可以使用 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))
... Whatis your name? It is lancelot. Whatis your quest? It is the holy grail. Whatis your favorite color? It is blue.