我的代码。我写了旋转列表的代码
s = 'abc'
lst = list(s)
for x in range(0,len(lst)):
lst = lst[-x:] + lst[:-x]
print (lst)
我的输出
['a', 'b', 'c']
['c', 'a', 'b']
['a', 'b', 'c']
预期结果
['a', 'b', 'c']
['c', 'a', 'b']
['b', 'c', 'a']
最佳答案
因为您正在覆盖您的原始列表,因此在第二次迭代中您正在旋转和额外的位置并以相同的列表结束。创建一个临时变量:
s = 'abc'
lst = list(s)
for x in range(0,len(lst)):
lst_ = lst[-x:] + lst[:-x]
print (lst_)
['a', 'b', 'c']
['c', 'a', 'b']
['b', 'c', 'a']
作为旁注 - 您可能会发现 collections.deque
对此类任务很有趣:
from collections import deque
d = deque(s)
for _ in range(len(s)):
print(d)
d.rotate()
deque(['a', 'b', 'c'])
deque(['c', 'a', 'b'])
deque(['b', 'c', 'a'])
关于python - 为什么我的代码不适用于 python list rotate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58185521/