所以,我在做 Project Euler 37
我需要分发一份 list
input: 2345 # 转换为函数内的列表
预期输出:[[3,4,5,2],[4,5,2,3],[5,2,3,4],[2,3,4,5]]
这是我的功能
def circulate(n): #2345
lst=list(str(n)) #[2,3,4,5]
res=[]
for i in range(len(lst)):
temp=lst.pop(0)
lst.append(temp)
print lst #print expected list
res.append(lst) #but doesn't append as expected
return res
print circulate(2345)
我的输出是:
['3', '4', '5', '2']
['4', '5', '2', '3']
['5', '2', '3', '4']
['2', '3', '4', '5']
[['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5']]
该函数每次都会正确打印 lst,但不会按预期追加。
我做错了什么?
最佳答案
您需要将列表的副本附加到res
:
res.append(lst[:])
您正在附加对正在更改的列表的引用;所有引用都反射(reflect)对一个对象所做的更改。
您可能想查看collections.deque()
反而;这个双端列表对象通过 .rotate()
方法支持高效旋转:
from collections import deque
def circulate(n):
lst = deque(str(n))
res = []
for i in range(len(lst)):
lst.rotate(1)
res.append(list(lst))
return res
关于python - Project Euler 37 的 Python 列表循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22711177/