Write a function in Python. Write a function that receives a list and an integer k. The function of the function is to reverse the elements before the integer k and return them together with the following elements.

Write a function in Python. Write a function that receives a list and an integer k. The function of the function is to reverse the elements before the integer k and return them together with the following elements.
The following is an example of a Python function that is used to reverse the elements before the integer k and return them together with the following elements:

def reverse_list(lst, k):
    if k >= len(lst):
        return lst[::-1]  # 如果k超出列表长度,直接返回整个列表的逆序
    else:
        return lst[k-1::-1] + lst[k:]  # 返回逆序的前k个元素与剩余元素的拼接
 # 示例用法
my_list = [1, 2, 3, 4, 5, 6]
k_value = 3
result = reverse_list(my_list, k_value)
print(result)

 In the above example, the reverse_list function receives a list lst and an integer k as arguments. If k is greater than or equal to the length of the list, the function directly returns the reverse order of the entire list. Otherwise, the function returns the concatenation of the first k elements and the remaining elements in reverse order.
In the example usage, we define a list my_list and an integer k_value, then call the reverse_list function and print the result. The output will be the concatenation of the first k elements and the remaining elements in reverse order.

Guess you like

Origin blog.csdn.net/airen3339/article/details/135435461