gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:30:12 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com