Create sublists in python

Asked

Viewed 370 times

1

I created the following code:

    self.buckets = [[], []]

    for i in self.keys:
        for ii in self.lista:
            if i % len(lista) == ii:
                self.buckets[ii].append(i)

That adds the elements of a list in the case "self.Keys", in another list "self.Buckets", according to the rest of the division by the "Len(list)". That is, let’s say the element of the time is "self.Keys = 10" and the "list = 0", as the rest of the division would be 0 this element must be added in the slot 0 of the list "self.Buckets".

The point is that the code above works, but it is not so practical, since I need to manually create all the sub-lists, e.g.:

self.buckets = [[], []]

Because of this, I wanted to have how to automate this creation of sub-lists, or something like.

1 answer

3


From what I understand, you need to create a list with n Sublists, all empty. You can do using list comprehension:

numeroDeSublistas = 4
self.buckets = [[] for _ in range(numeroDeSublistas)]

What returns:

[[], [], [], []]

As desired.

  • That’s exactly what it was, really !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.