Home >Backend Development >Python Tutorial >How to Replicate List Elements Multiplied Times?
Replicating List Elements Multiplied Times
The quest for a straightforward method to reiterate elements within a list several times often arises. This question aims to find an elegant solution similar to the following example:
x = [1, 2, 3, 4] n = 3 x1 = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Approaches like using x * n fall short, while for loops become cumbersome.
numpy to the Rescue
The optimal approach lies in utilizing NumPy's repeat function:
<code class="python">import numpy as np x1 = [1, 2, 3, 4] print(np.repeat(x1, 3)) # Output: # [1 1 1 2 2 2 3 3 3 4 4 4]</code>
This method effectively replicates each element in the original list x the specified number of times, n. Its简洁 and efficiency make it the ideal choice for this task.
The above is the detailed content of How to Replicate List Elements Multiplied Times?. For more information, please follow other related articles on the PHP Chinese website!