python - Project Euler 37 的 Python 列表循环

标签 python list

所以,我在做 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/

相关文章:

python - 使用 python 中的 ruby​​ gem/命令

python - 使用 tox 错误排序导入

c# - 在 List<Dictionary<string, object>> 中搜索一个值

c# - 如何将实际控件存储在列表中?

list - 获取Grails列表中的第一个元素

python - 为序列中某些事件之间的值创建一个列表。 。 。 Python

python - 如何在 Python 中为 for 循环中的某些数据分配图例?

Python *apropos* 命令

python - 将多索引 Pandas 系列和 DataFrame 相乘

c++ - 使用 STL 的列表对象创建 Stack