如何将给定列表中的每个子列表递增一?

问题描述 投票:0回答:1

假设有一个包含 n 个元素的列表,即 x = [23,25,3,45,67,89,67,45,4,6,...n]。什么数据结构和/或程序最适合将 x 转换为子列表列表,每个子列表的长度递增一,即 y = [[23],[25,3],[45,67,89 ],[67,45,4,6]].

换句话说,假设数组 A 的长度为 L,元素为 n。给定数组/列表 A[i] 的每个子集或子数组的 i 个间隔,哪种数据结构最适合将数组划分为子数组,每个子数组在每次迭代时将其元素递增 1,即 A[i] = [A[n+1] ],A[(n+1)+1],A[((n+1)+1)+1], ...]。假设第一个子数组 A[n+1] 只有一个元素。

python algorithm data-structures
1个回答
0
投票

您可以使用简单的编程方法Python,而不需要任何复杂的数据结构。

def create_increasing_sublists(array):
sublists = []
start = 0
length = 1

while start + length <= len(array):
    sublists.append(array[start:start + length])
    start += length
    length += 1

return sublists

# Example usage
x = [23, 25, 3, 45, 67, 89, 67, 45, 4, 6]  # Your list can be of any length
y = create_increasing_sublists(x)
print(y)
© www.soinside.com 2019 - 2024. All rights reserved.