📜  Python - 将列表转换为自定义重叠嵌套列表

📅  最后修改于: 2022-05-13 01:54:53.718000             🧑  作者: Mango

Python - 将列表转换为自定义重叠嵌套列表

给定一个列表,任务是编写一个Python程序,根据元素大小和重叠步长将其转换为自定义重叠嵌套列表。

例子:

方法#1:使用列表切片+循环

在这种情况下,行大小由切片操作管理,重叠步骤由 range() 中提到的步骤管理,同时使用循环进行迭代。

Python3
# Python3 code to demonstrate working of
# Convert List to custom overlapping Matrix
# Using list slicing + loop
  
# initializing list
test_list = [3, 5, 6, 7, 3, 9, 1, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing step, size
step, size = 2, 4
  
res = []
for idx in range(0, len(test_list), step):
  
    # slicing list
    res.append(test_list[idx: idx + size])
  
# printing result
print("The created Matrix : " + str(res))


Python3
# Python3 code to demonstrate working of
# Convert List to custom overlapping Matrix
# Using list comprehension
  
# initializing list
test_list = [3, 5, 6, 7, 3, 9, 1, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing step, size
step, size = 2, 4
  
# list comprehension used as shorthand to solve problem
res = [test_list[idx: idx + size] for idx in range(0, 
                                                   len(test_list), 
                                                   step)]
  
# printing result
print("The created Matrix : " + str(res))


输出:

方法#2:使用列表理解

在这种情况下,使用与上述方法类似的功能以及使用列表理解进行速记的变体。

蟒蛇3

# Python3 code to demonstrate working of
# Convert List to custom overlapping Matrix
# Using list comprehension
  
# initializing list
test_list = [3, 5, 6, 7, 3, 9, 1, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing step, size
step, size = 2, 4
  
# list comprehension used as shorthand to solve problem
res = [test_list[idx: idx + size] for idx in range(0, 
                                                   len(test_list), 
                                                   step)]
  
# printing result
print("The created Matrix : " + str(res))

输出: