如何有效率地多次重複列表元素?

Susan Sarandon
發布: 2024-10-17 14:03:29
原創
310 人瀏覽過

How to Efficiently Repeat List Elements Multiple Times?

Efficiently Repeating List Elements

When faced with the task of repeating each element of a list multiple times, many approaches come to mind. However, finding a simple yet computationally efficient solution can be challenging.

One common approach, mentioned in the question, involves using the "*" operator. However, as pointed out, it simply multiplies the list by the specified number, resulting in an undesirable outcome. Another attempt, involving loops and nested multiplication, is also inadequate.

The most efficient solution lies in leveraging the power of numpy, a powerful library for numerical operations. Using the numpy.repeat function, we can achieve the desired result with utmost simplicity.

For example, consider the input list x = [1,2,3,4] and the desired repetition factor n = 3. To create a new list x1 that contains each element of x repeated three times, we can use the following code:

<code class="python">import numpy as np
x1 = np.repeat(x, 3)</code>
登入後複製

The output, as expected, will be:

array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
登入後複製

Numpy's repeat function is not only concise and easy to use but also highly efficient, making it the ideal choice for this task.

以上是如何有效率地多次重複列表元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!