Python - 将列表转换为自定义重叠嵌套列表
给定一个列表,任务是编写一个Python程序,根据元素大小和重叠步长将其转换为自定义重叠嵌套列表。
例子:
Input: test_list = [3, 5, 6, 7, 3, 9, 1, 10], step, size = 2, 4
Output: [[3, 5, 6, 7], [6, 7, 3, 9], [3, 9, 1, 10], [1, 10]]
Explanation: Rows sliced for size 4, and overcoming started after 2 elements of current row.
Input: test_list = [3, 5, 6, 7, 3, 9, 1, 10], step, size = 2, 3
Output: [[3, 5, 6], [6, 7, 3], [3, 9, 1], [1, 10]]
Explanation: Rows sliced for size 3, and overcoming started after 2 elements of current row.
方法#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))
输出:
The original list is : [3, 5, 6, 7, 3, 9, 1, 10]
The created Matrix : [[3, 5, 6, 7], [6, 7, 3, 9], [3, 9, 1, 10], [1, 10]]
方法#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))
输出:
The original list is : [3, 5, 6, 7, 3, 9, 1, 10]
The created Matrix : [[3, 5, 6, 7], [6, 7, 3, 9], [3, 9, 1, 10], [1, 10]]