简体   繁体   English

Python:更改实例列表中的元素位置

[英]Python: change elements position in a list of instances

I have a list that is made of class instances:我有一个由类实例组成的列表:

MyList = [<instance1>, <instance2>, <instance3>]

I would like to change the position of the third element, <instance3> , that should now stay in the position index = 1, so with the following output:我想更改第三个元素<instance3>的位置,它现在应该保持在 index = 1 的位置,因此输出如下:

MyList = [<instance1>, <instance3>, <instance2>]

I have built a simple example that works:我已经建立了一个简单的例子:

a = [1,2]
b = [3,4]
c = [5,6]
d = [a,b,c]

The code above gives me the following print d output:上面的代码给了我以下print d输出:

d = [[1, 2], [3, 4], [5, 6]]

I'm able to swap the elements (1) and (2) with the following method:我可以使用以下方法交换元素 (1) 和 (2):

d.remove(c)
d.insert(c,1)

which gives me the following output (that is the one that I want):这给了我以下输出(这是我想要的):

d = [[1, 2], [5, 6], [3, 4]]

However, when I try to make the same with my list of instances, I get the following AttributeError:但是,当我尝试对我的实例列表进行相同处理时,出现以下 AttributeError:

AttributeError: entExCar instance has no attribute '__trunc__'

Someoene can tell me if I'm wrong in the method (example: you cannot use this technique with list of instances, you should rather do "this or that") or in the way I'm setting the code?有人可以告诉我我是否在方法中错了(例如:您不能将这种技术用于实例列表,您应该做“这个或那个”)或我设置代码的方式? The following script is the actual code I'm trying to run getting the error:以下脚本是我尝试运行时出现错误的实际代码:

newElement = self.matriceCaracteristiques[kk1]    
self.matriceCaracteristiques.remove(newElement) 
self.matriceCaracteristiques.insert(newElement,nbConditionSortieLong)   

Thanks in advance.提前致谢。

EDIT: SOME DETAILS MORE编辑:更多细节

entExCar is the class which is being instatiating self.matriceCaracteristiques is the list I want to manipulate newElement is the element I want to remove from its original position (kk1) and put back into the new position (nbConditionSortieLong). entExCar 是正在初始化 self.matriceCaracteristiques 的类是我想要操作的列表 newElement 是我想要从其原始位置 (kk1) 中删除并放回新位置 (nbConditionSortieLong) 的元素。

First, I didn't get the error you mentioned.首先,我没有收到您提到的错误。
Second, it seems that you made a mistake in using insert , should be insert(1, c) rather than insert(c, 1) , see docs其次,您似乎在使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM