Skip to main content
 首页 » 编程设计

python之为什么这不返回给定数字的旋转

2025年05月04日9dyllove98

我会尝试用一个例子来解释我想做什么:

Number = ["1","9","7"]   

所以我希望它返回:

[["1","9","7"],["9","7","1"],["7","1","9"]]   

我得到的是:

[["7","1","9"],["7","1","9"],["7","1","9"]] 

由于某些不明原因,它用最后一个结果替换了我的第一个结果。

def Get_Rotations(Number): 
    Rotations = [] 
    x = 0 
    while x < len(Number): 
        Number.insert(0,Number.pop()) 
        Rotations.append(Number) 
        x += 1 
    print(Rotations) 
    return Rotations   

请您参考如下方法:

您必须创建 Number 的副本。您在每次迭代中操作相同的列表,并将该列表附加三次到 Rotations。因此,您会在“结束状态”中看到三次 Number。

Rotations.append(list(Number)) 

这个小改动应该可以解决问题! ;-)