python - 数字python的旋转

标签 python

为了找到一个数字的旋转,我写了如下代码

def rotation(N):
    A=[]
    for i in range(len(N)):
        y=N.pop(0)
        N.append(y)
        A.append(N)
    return A
K=[1,9,7]
r=rotation(K)
print(r)

但它给了我这样的输出:

A=[[1, 9, 7], [1, 9, 7], [1, 9, 7]]

但应该是

A=[[1,9,7],[9,7,1],[7,1,9]]

我不明白为什么会这样 谢谢

最佳答案

使用简单的列表切片:

def rotation(N):
    output = []
    for i in range(len(N)):
        output.append(N[i:] + N[:i])
    return output

K=[1,9,7]
r=rotation(K)
print(r)
# [[1, 9, 7], [9, 7, 1], [7, 1, 9]]

关于python - 数字python的旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50570334/

相关文章:

Python:线程什么时候终止?显然不是(立即)返回

python - Python中根据字符分解子字符串

python - 如何计算每组中最常见的组合

python - 如何在 Bottle 模板中输出未转义的 python 列表?

python - 我可以在不阻塞执行主线程的情况下以编程方式启动 WSGI 应用程序服务器吗?

python - 在 Eclipse Pydev 中提交哪些内容到源代码控制

python - 在不丢失数据的情况下合并和取消合并对象的最佳方式

python - 行和列中唯一的条目的组合

python - 使用 django 表单创建新文件

python - Pandas SQL 等价于 update where group by