[英]Change position of elements in a list so they cross match another list in Python
[英]Python: change elements position in a list of instances
我有一个由类实例组成的列表:
MyList = [<instance1>, <instance2>, <instance3>]
我想更改第三个元素<instance3>
的位置,它现在应该保持在 index = 1 的位置,因此输出如下:
MyList = [<instance1>, <instance3>, <instance2>]
我已经建立了一个简单的例子:
a = [1,2]
b = [3,4]
c = [5,6]
d = [a,b,c]
上面的代码给了我以下print d
输出:
d = [[1, 2], [3, 4], [5, 6]]
我可以使用以下方法交换元素 (1) 和 (2):
d.remove(c)
d.insert(c,1)
这给了我以下输出(这是我想要的):
d = [[1, 2], [5, 6], [3, 4]]
但是,当我尝试对我的实例列表进行相同处理时,出现以下 AttributeError:
AttributeError: entExCar instance has no attribute '__trunc__'
有人可以告诉我我是否在方法中错了(例如:您不能将这种技术用于实例列表,您应该做“这个或那个”)或我设置代码的方式? 以下脚本是我尝试运行时出现错误的实际代码:
newElement = self.matriceCaracteristiques[kk1]
self.matriceCaracteristiques.remove(newElement)
self.matriceCaracteristiques.insert(newElement,nbConditionSortieLong)
提前致谢。
编辑:更多细节
entExCar 是正在初始化 self.matriceCaracteristiques 的类是我想要操作的列表 newElement 是我想要从其原始位置 (kk1) 中删除并放回新位置 (nbConditionSortieLong) 的元素。
首先,我没有收到您提到的错误。
其次,您似乎在使用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]]
关于什么
MyList.insert(index_to_insert,MyList.pop(index_to_remove))
values[0], values[1] = values[1], values[0]
这对我来说很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.