假设我们有一个列表mylist = ['a', 'b', 'c']
,我们想生成另一个类似的列表:['a:1', 'a:2', 'b:1', 'b:2', 'c:1', 'c:2']
,它基本上将':1'
和':2'
附加到mylist
的每个元素。
如果可能的话,我想知道如何使用列表理解有效地做到这一点?
像这样:
['%s:%d' % (e, i) for e in mylist for i in (1, 2)]
我认为最有效的方法是使用itertools.product
:
http://docs.python.org/2/library/itertools.html#itertools.product
from itertools import product
mylist = ['a', 'b', 'c']
mysuffixes = [':1', ':2']
result = [x+y for x, y in product(mylist, mysuffixes)]
具体的构造可能会因常量的定义方式而异。
>>> a=['a','b','c']
>>> b=[1,2]
>>> import itertools
>>> ['%s:%s' % (x,y) for x,y in itertools.product(a,b)]
['a:1', 'a:2', 'b:1', 'b:2', 'c:1', 'c:2']
In [4]: mylist = ['a', 'b', 'c']
In [5]: list(itertools.chain.from_iterable([[e+":1", e+":2"] for e in mylist]))
Out[5]: ['a:1', 'a:2', 'b:1', 'b:2', 'c:1', 'c:2']
此概念与itertools.product
相同
>>> from itertools import product
>>> list(product(mylist, ('1', '2')))
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2'), ('c', '1'), ('c', '2')]
当产品返回元组时,您必须将元组与:
连接起来,我认为这个解决方案是最清晰的:
>>> map(':'.join, product(mylist, ('1', '2')))
['a:1', 'a:2', 'b:1', 'b:2', 'c:1', 'c:2']