简体   繁体   English

如何为列表中的项目分配类对象? (蟒蛇)

[英]How to assign a class object to a item in a list? (python)

I defined a class with 3 objects inside of it: 我定义了一个包含3个对象的类:

class abc():
     __slots___ = ('1','2',3')

From here, I made a list containing around a thousand elements: 从这里,我列出了包含大约一千个元素的列表:

lst = [[abc,dfg,9292],[ksdj,lkjsd,9239],...]

The third element inside each element is always a number. 每个元素内的第三个元素始终是数字。 I want to assign the object called 3 in my class to that third element so that I can sort the list. 我想将类中名为3的对象分配给该第三个元素,以便可以对列表进行排序。

To clarify some misconceptions object 3 is actually quantity. 为了澄清一些误解,对象3实际上是数量。 Therefore, the third element in each element is considered a quantity. 因此,将每个元素中的第三个元素视为一个数量。

It's unclear whether you're trying to sort the list, create instances of abc from elements in your list, or something totally different. 目前尚不清楚您是要对列表进行排序,还是要根据列表中的元素创建abc实例,还是要完全不同。

Assuming you wanted to sort your list by the 3rd element of each sublist: 假设您想按每个子列表的第3个元素对列表进行排序:

lst.sort(key = lambda x: x[2])

would sort your list in place. 将对您的列表进行排序。

If you want to create an object of type abc from each element in your list, you need to figure out what you're doing with the data from each list element. 如果要从列表中的每个元素创建类型为abc的对象,则需要弄清楚对每个列表元素中的数据正在做什么。 If you simply want to store it as instance variables, you could do something like this: 如果只想将其存储为实例变量,则可以执行以下操作:

class ABC():
    __slots__ = ('a', 'b', 'c')
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

obj_list = [ABC(*x) for x in lst]

You could then sort this resulting list of objects if that's what you want. 然后,如果需要的话,您可以对结果列表进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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