使用步长值将列表转换为列表列表的Python程序
给定一个列表,这里的任务是编写一个Python程序,该程序可以使用此处通过 K 表示的步长值将列表拆分为列表列表。
Input : test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8], K = 3
Output : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]
Explanation : 5, 2 and 9 are 0th, 3rd and 6th element respectively, and hence ( difference 3 ) grouped together.
Input : test_list = [5, 6, 3, 2, 7, 1], K = 3
Output : [[5, 2], [6, 7], [3, 1]]
Explanation : 5 and 2 are 0th and 3rd element respectively, and hence ( difference 3 ) grouped together.
方法 1:使用循环和切片
其中,使用循环根据需要跳过数字,并使用切片提取每个后续跳过的切片列表并附加到结果。
例子:
Python3
# initializing list
test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing skips
K = 3
res = []
for idx in range(0, K):
# 3rd arg. of slicing skips by K
res.append(test_list[idx::K])
# printing result
print("Stepped splitted List : " + str(res))
Python3
# initializing list
test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing skips
K = 3
# list comprehension used as one liner
res = [test_list[idx::K] for idx in range(0, K)]
# printing result
print("Stepped splitted List : " + str(res))
输出:
The original list is : [5, 6, 3, 2, 7, 1, 9, 10, 8]
Stepped splitted List : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]
方法 2:使用列表理解和切片
与上述方法类似,唯一的区别是对迭代任务使用列表理解而不是用于速记替代的循环。
例子:
蟒蛇3
# initializing list
test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing skips
K = 3
# list comprehension used as one liner
res = [test_list[idx::K] for idx in range(0, K)]
# printing result
print("Stepped splitted List : " + str(res))
输出:
The original list is : [5, 6, 3, 2, 7, 1, 9, 10, 8]
Stepped splitted List : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]