我正在学习itertools,并遇到了一个有趣的问题。
如何获得以下结果?
nums = [1,2,3,4]
# logic: i+1 th number is repeated i times.
2 is repeated 1 times and 4 is repeated 3 times.
required = [2,4,4,4]
import itertools
nums = [1,2,3,4]
nums[::2] # [1,3]
nums[1::2] # [2,4]
* 2 is repeated 1 times
* 4 is repeated 3 times and makes [2,4,4,4]
list(itertools.starmap(itertools.repeat, zip(nums[::2],nums[1::2])))
Gives,
[repeat(1, 2), repeat(3, 4)]
How to get:
required = [2,4,4,4]
From: [1,2,3,4]
To: [2,4,4,4]
We can use itertools, list comp and numpy.
您不需要itertools。列表理解和邮政编码就足够了:
nums = [1,2,3,4]
rnums = [ rn for r,n in zip(nums[::2],nums[1::2]) for rn in r*[n] ]
print(rnums) # [2, 4, 4, 4]