2017-06-02 65 views
1

运行下面的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属性相同)。

+1

你在找什么样的预期答案?你是否想要改变名单? –

回答

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] 

那么,你的旋转将被保存。

+0

晶莹剔透的解释,谢谢! –

0

您传回旋转列表,而不是重新分配回self.input的:

def rotate(self): 
    self.input = self.input[1:] + self.input[: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实际上是一个数组列表。

0

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

如果你不需要更新它,因为一旦你更新了,那么所有其他功能也将得到改变,你可能不喜欢。

所以做到这一点 -

rotated_board = board.rotate() 
print(rotated_board) 

让我知道,如果它的工作!