你可以使用
zip
和列表解析来完成这个任务:
>>> a = ['x','y','z']
>>> b = [1,2,3]
>>> [[x]*y for x,y in zip(a,b)]
[['x'], ['y', 'y'], ['z', 'z', 'z']]
或:
>>> [[x for _ in xrange(y)] for x,y in zip(a,b)]
[['x'], ['y', 'y'], ['z', 'z', 'z']]
zip
会先在内存中创建整个列表,如果要获得迭代器,请使用itertools.izip
如果a
包含可变对象,如列表或列表的列表,则可能需要在此处使用copy.deepcopy
,因为修改一个副本也会改变其他副本。
>>> from copy import deepcopy as dc
>>> a = [[1 ,4],[2, 5],[3, 6, 9]]
>>> f = [[dc(x) for _ in xrange(y)] for x,y in zip(a,b)]
>>> [[id(z) for z in x] for x in f]
[[172880236], [172880268, 172880364], [172880332, 172880492, 172880428]]
timeit
比较(忽略导入):
>>> a = ['x','y','z']*10**4
>>> b = [100,200,300]*10**4
>>> %timeit [[x]*y for x,y in zip(a,b)]
1 loops, best of 3: 104 ms per loop
>>> %timeit [[x]*y for x,y in izip(a,b)]
1 loops, best of 3: 98.8 ms per loop
>>> %timeit map(lambda v: [v[0]]*v[1], zip(a,b))
1 loops, best of 3: 114 ms per loop
>>> %timeit map(list, map(repeat, a, b))
1 loops, best of 3: 192 ms per loop
>>> %timeit map(list, imap(repeat, a, b))
1 loops, best of 3: 211 ms per loop
>>> %timeit map(mul, [[x] for x in a], b)
1 loops, best of 3: 107 ms per loop
>>> %timeit [[x for _ in xrange(y)] for x,y in zip(a,b)]
1 loops, best of 3: 645 ms per loop
>>> %timeit [[x for _ in xrange(y)] for x,y in izip(a,b)]
1 loops, best of 3: 680 ms per loop
itertools.izip
。 - kirelaginfor
循环本质上很慢,并且在 MCMC 中最好避免使用 - 仍然盲目地听从任何我听到的建议 :s - user2444731