Python切片 |在给定大小的组中反转数组
给定一个数组,反转由连续 k 个元素组成的每个子数组。
例子:
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
Output:
[3, 2, 1, 6, 5, 4, 9, 8, 7]
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 5
Output:
[5, 4, 3, 2, 1, 8, 7, 6]
Input:
arr = [1, 2, 3, 4, 5, 6]
k = 1
Output:
[1, 2, 3, 4, 5, 6]
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 10
Output:
[8, 7, 6, 5, 4, 3, 2, 1]
对于这个问题,我们有现有的解决方案,请参考 Reverse an array in groups of given size 链接。我们可以使用列表切片和 reversed()函数在Python中快速解决这个问题。下面的示例将让您更好地理解方法。
例子:
# function to Reverse an array in groups of given size
def reverseGroup(input,k):
# set starting index at 0
start = 0
# run a while loop len(input)/k times
# because there will be len(input)/k number
# of groups of size k
result = []
while (start
输出:
[5, 4, 3, 2, 1, 8, 7, 6]
使用直接函数
# function to Reverse an array in groups of given size
def reverseGroup(a, k):
# take an empty list
res = []
# iterate over the list with increment of
# k times in each iteration
for i in range(0, len(a), k):
# reverse the list in each iteration over
# span of k elements using extend
res.extend((a[i:i + k])[::-1])
print(res)
# Driver program
if __name__ == "__main__":
input = [1, 2, 3, 4, 5, 6, 7, 8]
k = 5
reverseGroup(input, k)
输出:
[5, 4, 3, 2, 1, 8, 7, 6]