簡體   English   中英

如何擴展列表以在 python 中重復到大小 n?

[英]How do you expand a list to repeat to size n in python?

假設我有一個列表[0.67045, 0.662866]並且我想將其擴展為 8 號並重復直到達到大小;

[0.67045, 0.662866,0.67045, 0.662866, 0.67045, 0.662866,0.67045, 0.662866]

如果我給它一個大小為 4 的列表; [0.850009, 0.439764, 0.849811, 0.440243]它將變成

[0.850009, 0.439764, 0.849811, 0.440243, 0.850009, 0.439764, 0.849811, 0.440243]

並且大小為 8 的列表根本不會擴展,因為它等於我想要的大小。

這是如何在 python 中完成的?

一個沒有循環的簡單方法是復制元素,直到你確定你有足夠的元素,然后修剪掉多余的元素。

wanted_size = 11
arr = ['a', 'b']
result = arr * ceil(wanted_size / len(arr))  # expand to at least the wanted size
result = result[:wanted_size]  # trim off the modulus

不是 memory 高效但簡單。

arr = [123,321]
cap = 8
(arr * cap)[:cap]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM