python rotate函数
时间: 2023-10-19 11:25:48 浏览: 241
`rotate` 函数可以用来旋转列表或字符串中的元素。它接受两个参数:要旋转的对象和旋转的步数。正数表示向右旋转,负数表示向左旋转。
以下是一个示例代码,演示了如何使用 `rotate` 函数来旋转列表:
```python
def rotate(lst, steps):
length = len(lst)
steps = steps % length # 处理 steps 大于列表长度的情况
if steps == 0:
return lst
rotated_lst = lst[-steps:] + lst[:-steps]
return rotated_lst
# 示例用法
my_list = [1, 2, 3, 4, 5]
rotated_list = rotate(my_list, 2) # 向右旋转2步
print(rotated_list) # 输出: [4, 5, 1, 2, 3]
```
类似地,你也可以使用这个函数来旋转字符串。例如:
```python
def rotate(string, steps):
length = len(string)
steps = steps % length
if steps == 0:
return string
rotated_string = string[-steps:] + string[:-steps]
return rotated_string
# 示例用法
my_string = "Hello, World!"
rotated_string = rotate(my_string, -3) # 向左旋转3步
print(rotated_string) # 输出: "lo, World!Hel"
```
希望这可以帮助到你!如果你有任何其他问题,请随时提问。
阅读全文
相关推荐
















