旋转列表不起作用?

时间:2017-06-02 21:00:04

标签: python

运行以下python代码:

class MarblesBoard:
    def __init__(self, marbles):
        self.input = list(marbles) 
        print(marbles)
    def switch(self):
        self.input[1], self.input[0] = self.input[0], self.input[1]
        #print self.input
    def rotate(self):
        return self.input[1:] + self.input[:1]
        #print self.input
    def is_solved(self):
        if all(self.input[i] <= self.input[i+1] for i in range(len(self.input)-1)):
            return True
            print "True"
        else:
            print "Not solved!"

board = MarblesBoard((3,6,7,4,1,0,8,2,5))
board.switch()
print board.input
board.rotate()
print board.input

board.is_solved()

似乎不起作用。 board.switch()方法在调用时可以正常工作;但是,rotate方法不起作用(输出board.input属性与输入board.input属性相同)。

4 个答案:

答案 0 :(得分:2)

在当前状态下,您的rotate函数永远不会将自身保存回self.input。你只需返回新状态。

def rotate(self):
    return self.input[1:] + self.input[:1]

应该更改为此(类似于您在switch函数中执行的操作):

def rotate(self):
    self.input = self.input[1:] + self.input[:1]

然后,您的轮换将被保存。

答案 1 :(得分:1)

正如其他人所指出的,您的代码失败了,因为您丢弃了在rotate方法中创建的新列表。但是,您可以考虑使用collections.deque而不是列表:

>>> from collections import deque
>>> d = deque(range(10))
>>> d
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> d.rotate(-1)
>>> d
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])

请注意,这可以就地使用。这在deque中更有效地实现,因为它是双向链表,而list实际上是数组列表。

答案 2 :(得分:0)

您将返回轮换列表,而不是将其重新分配回self.input

def rotate(self):
    self.input = self.input[1:] + self.input[:1]

答案 3 :(得分:0)

如果您需要更改类对象(输入)本身,请按照上面的建议进行更改。

如果您不需要更新它,因为一旦您更新,所有其他功能也将被更改,您可能不喜欢。

这样做 -

rotated_board = board.rotate()
print(rotated_board)

请告诉我,如果有效!