我有一个由类实例组成的列表:
MyList = [<instance1>, <instance2>, <instance3>]
Run Code Online (Sandbox Code Playgroud)
我想更改第三个元素的位置,<instance3>现在应该保持在 index = 1 的位置,因此输出如下:
MyList = [<instance1>, <instance3>, <instance2>]
Run Code Online (Sandbox Code Playgroud)
我已经建立了一个简单的例子:
a = [1,2]
b = [3,4]
c = [5,6]
d = [a,b,c]
Run Code Online (Sandbox Code Playgroud)
上面的代码给了我以下print d输出:
d = [[1, 2], [3, 4], [5, 6]]
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方法交换元素 (1) 和 (2):
d.remove(c)
d.insert(c,1)
Run Code Online (Sandbox Code Playgroud)
这给了我以下输出(这是我想要的):
d = [[1, 2], [5, 6], [3, 4]]
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试对我的实例列表进行相同处理时,出现以下 AttributeError:
AttributeError: entExCar instance has no attribute '__trunc__'
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我我是否在方法中错了(例如:您不能将这种技术与实例列表一起使用,您应该做“这个或那个”)或我设置代码的方式?以下脚本是我尝试运行时出现错误的实际代码:
newElement = self.matriceCaracteristiques[kk1]
self.matriceCaracteristiques.remove(newElement)
self.matriceCaracteristiques.insert(newElement,nbConditionSortieLong)
Run Code Online (Sandbox Code Playgroud)
提前致谢。
编辑:更多细节
entExCar 是正在初始化 self.matriceCaracteristiques 的类是我要操作的列表 newElement 是我要从其原始位置 (kk1) 中删除并放回新位置 (nbConditionSortieLong) 的元素。
小智 8
关于什么:
MyList.insert(index_to_insert,MyList.pop(index_to_remove))
Run Code Online (Sandbox Code Playgroud)
首先,我没有收到您提到的错误。
其次,您似乎在使用时犯了一个错误insert,应该是insert(1, c)而不是insert(c, 1),请参阅文档
>>> d = [[1, 2], [5, 6], [3, 4]]
>>> c = d[1]
>>> d.remove(c)
>>> d
[[1, 2], [3, 4]]
>>> d.insert(c, 1)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
d.insert(c, 1)
TypeError: 'list' object cannot be interpreted as an integer
>>> d.insert(1, c)
>>> d
[[1, 2], [5, 6], [3, 4]]
Run Code Online (Sandbox Code Playgroud)