Python中的Project Euler 37列表循环

2024-07-02 12:18:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我在做Project Euler 37

我需要传阅一份名单

输入: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)

我的输出是:

^{pr2}$

函数每次都正确地打印lst,但没有按预期追加。在

我做错什么了?在


Tags: 函数功能project列表defrestemplist
1条回答
网友
1楼 · 发布于 2024-07-02 12:18:26

您需要将列表的副本附加到res

res.append(lst[:])

而是将引用附加到要更改的列表;所有引用都反映对一个对象所做的更改。在

您可能需要查看^{};这个双端列表对象支持使用.rotate()方法进行有效的旋转:

^{pr2}$

相关问题 更多 >