python - 为什么我的代码不适用于 python list rotate

标签 python list

我的代码。我写了旋转列表的代码

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/

相关文章:

python - 如何读取包含分组数据的 CSV,其中每个组都有不同的列?

python - 在 Python 中访问 Firefox 3 cookie

python - 再次使用该值作为索引以避免局部变量时列表交换两个元素失败

c# - 使用另一个列表的内容过滤一个列表

java - 在数字第一次出现时分割字符串的最有效方法?

list - 以 'raw' ./2 格式显示列表

python - 如何将 Python 连接到 Db2

python - 如何判断返回的光标是否是 App Engine 中的最后一个光标

python - 将输入限制为仅整数(文本使 PYTHON 程序崩溃)

performance - 将谓词应用于 Prolog : requesting advice on implementation choices 中列表的子集