重复数组中的值直到指定长度 [英] Repeat values in array until specific length

查看:65
本文介绍了重复数组中的值直到指定长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要某种功能或小技巧来解决我的问题。

I need some kind of function or little tip for my problem.

所以我得到了一个列表,比如说
[1,2,3 ,4]
,但我需要将此数组加长并重复相同的元素,所以假设我需要一个长度为10的数组,因此它变为:
[1,2,3,4,1,2,3,4,1,2]

So I got a list let's say [1,2,3,4] but I need this array to be longer with the same elements repeated so let's say I need an array of length 10 so it becomes: [1,2,3,4,1,2,3,4,1,2]

所以我需要使用相同的扩展列表值与列表中的顺序相同

So I need to extend the list with the same values as in the list in the same order

returnString = the array or string to return with extended elements
array = the basic array which needs to be extended
length = desired length

编辑:

returnString = ""
array = list(array)
index = 0
while len(str(array)) != length:
    if index <= length:
        returnString += array[index]
        index += 1
    else:
        toPut = index % length
        returnString.append(array[toPut])
        index += 1
return returnString


推荐答案

您可以使用 itertools.cycle 重复遍历列表,并根据需要获取任意数量的值。

You can use itertools.cycle to iterate repeatedly over the list, and take as many values as you want.

from itertools import cycle

lst = [1, 2, 3, 4]
myiter = cycle(lst)
print([next(myiter) for _ in range(10)])


[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]

您也可以使用它来扩展列表(如果您追加了到最后,虽然您无法遍历它,但是删除项目是行不通的。)

You can also use it to extend the list (it doesn't matter if you append to the end while you are iterating over it, although removing items would not work).

from itertools import cycle

lst = [1, 2, 3, 4]
myiter = cycle(lst)
for _ in range(6):
    lst.append(next(myiter))
print(lst)


[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]

这篇关于重复数组中的值直到指定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆