0

I defined a class with 3 objects inside of it:

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.

To clarify some misconceptions object 3 is actually quantity. Therefore, the third element in each element is considered a quantity.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
steve
  • 61
  • 1
  • 1
  • 6
  • 1
    Which language is this? – Étienne Miret Oct 10 '13 at 22:16
  • Looks like python to me... @steve correct me if I'm wrong please. – dwerner Oct 10 '13 at 22:21
  • What is the object called 3 in your class? You can't have a variable name like that. Can you explain what you mean by "from here, I made a list containing around a thousand elements?" I really don't understand what you've written – YXD Oct 10 '13 at 22:22
  • For `__slots__` newbs (like me) http://stackoverflow.com/questions/472000/python-slots – dwerner Oct 10 '13 at 22:24
  • Mr E, I opened a file that contained around 1000 lines. Each line had a element that has 3 elements in it. [abc, dfg, 123]. The 123 is the Quantity that i'm trying to sort. – steve Oct 10 '13 at 22:30
  • 1
    @steve Any particular reason you can't just sort the list directly? I'm not following why you're trying to make objects here... – Jon Clements Oct 10 '13 at 22:37

1 Answers1

1

It's unclear whether you're trying to sort the list, create instances of abc from elements in your list, or something totally different.

Assuming you wanted to sort your list by the 3rd element of each sublist:

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. 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.

dckrooney
  • 3,041
  • 3
  • 22
  • 28