重复数组中的值直到特定长度

Repeat values in array until specific length

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

所以我得到了一个列表让我们说 [1,2,3,4] 但是我需要这个数组更长,重复相同的元素所以假设我需要一个长度为 10 的数组,所以它变成: [1,2,3,4,1,2,3,4,1,2]

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

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

试试这个:

n = 10
lst =[1,2,3,4]
new_lst = [lst[i%len(lst)] for i in range(n)]
print(new_lst)

输出:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
NumOfValues = int(input("Number of Values: "))
List1 = [1,2,3,4]
List2 = []
Count = 0
while len(List2) < NumOfValues:
    List2.append(List1[Count])
    Count += 1
    if Count > len(List1) - 1:
        Count = 0
print(List2)

我给你一个提示:

如果你有这个 array [1,2,3,4],那么你可以创建一个单独的 newArray 来获取这个值,并用这个重复的值填充 newArray。 如何?环形!我认为 for 可以对你这样做,只需将 arraynewArray 指向它就知道它会填充哪个。

您可以使用 itertools.cycle 重复遍历列表,并取任意多的值。

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]

您还可以使用它来扩展列表(在遍历列表时附加到末尾并不重要,尽管删除项目不起作用)。

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]

一种方法可以是:

遍历所需的 length - len(x_lst),因此您有 10 - 4 = 6(要添加的新元素)。现在,由于列表元素应该重复,您可以通过索引 (0,1,2,3,4,5).

随时附加 x_lst 元素
x = [1,2,3,4]

length = 10

for i in range(length - len(x)):
    x.append(x[i])

print(x)

输出:

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

itertools.cycleitertools.islice 很简单:

from itertools import cycle, islice

input = [1, 2, 3, 4]
output = list(islice(cycle(input), 10))

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

首先将列表乘以需要重复的次数。如果这不是所需的长度,请使用列表的适当部分对其进行扩展。

old_len = len(original)
new_len = 10
result = original * new_len // old_len
if new_len % old_len != 0:
    result += original[:new_len % old_len]