当我尝试使用 rotate(( 从集合和 deque 中移动列表中的项目时,我不断收到错误。我使用了集合和 deque,以便将每个元素移动 1 或 n。
from collections import deque
array= deque["a","b","c","d","e"]
array.rotate(1)
print(array)
执行时出现以下错误
array= deque["a","b","c","d","e"]
TypeError: 'type' object is not subscriptable
deque
是一个类的名称:
>>> deque
<class 'collections.deque'>
因此,deque["a","b","c","d","e"]
在语法上不正确。您可以通过实例化来创建新的deque
对象:deque(["a","b","c","d","e"])
此对象具有可以调用的rotate
方法:
>>> array.rotate(1)
>>> print(array)
deque(['e', 'a', 'b', 'c', 'd'])
如果需要列表对象,可以执行以下操作:list(array)