How to Replicate List Elements Multiplied Times?

Susan Sarandon
Release: 2024-10-17 14:08:29
Original
371 people have browsed it

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]
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!