Split sublist in python

Asked

Viewed 265 times

0

Good team, I have a method that receives a list and from it creates sub-list and attaches in Buckets:

def indexar(self, keys):
    buckets = [[] for _ in range(10)]

    for i in keys:
        for ii in range(10):
            if i % 10 == ii:
                buckets[ii].append(i)

When I pass the list:

keys = list(range(0, 100)

Return:

Buckets[0] = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

From this I wanted to split all Buckets[] sub-lists to size 3, example:

nova[0] = [[0, 10, 20], [30, 40, 50], [60, 70, 80], [90]]

I’m trying this way:

   novo = list()
    for i in range(0, len(buckets)):
        for ii in range(0, len(buckets[i]), 3):
            novo.append(list(buckets[i][ii:ii + 3]))
    return novo

Only this way she only slices the sub-lists, but she doesn’t connect. Complete code:

def indexar(self, keys):
    buckets = []
    for _ in range(10):
        buckets.append([])

    for i in keys:
        for ii in range(10):
            if i % 10 == ii:
                buckets[ii].append(i)

    nova = []

    for i in range(0, len(buckets)):
        for ii in range(0, len(buckets[i]), 3):
            nova.append(list(buckets[i][ii:ii + 3]))
    return nova
  • You could put an example of an input list and an output list you want to get?

  • I edited the question, can take a look if it became clearer ?

2 answers

2


According to entry and exit:

def indexar(values):
    # Contador iniciado em 0
    count = 0
    # Lista com até 10 listas
    buckets = [[] for _ in range(10)]

    # O índice vai de 0 até o tamanho da lista buckets
    for r in range(0, len(buckets)):
        # O índice vai de 0 até o tamanho da lista values
        for s in range(0, len(values)):
            # Verifica se r é multiplo de 3
            if s % 3 == 0:
                # Faz uma list comprehension pra armazenar em buckets no índice r
                # os valores dentro do range atual começando pelo 
                # índice s e finalizando no índice s + 3
                # e somando cada valor de values com o contador
                buckets[r].append([v + count for v in values[s:s + 3]])
        # Incrementa ao contador + 1
        count += 1
    # Retorna lista
    return buckets

foo = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
print(indexar(foo))

# Saída: [[[0, 10, 20], [30, 40, 50], [60, 70, 80], [90]], [[1, 11, 21], [31, 41, 51], [61, 71, 81], [91]], [[2, 12, 22], [32, 42, 52], [62, 72, 82], [92]], [[3, 13, 23], [33, 43, 53], [63, 73, 83], [93]], [[4, 14, 24], [34, 44, 54], [64, 74, 84], [94]], [[5, 15, 25], [35, 45, 55], [65, 75, 85], [95]], [[6, 16, 26], [36, 46, 56], [66, 76, 86], [96]], [[7, 17, 27], [37, 47, 57], [67, 77, 87], [97]], [[8, 18, 28], [38, 48, 58], [68, 78, 88], [98]], [[9, 19, 29], [39, 49, 59], [69, 79, 89], [99]]]
  • Victor, in this case only occurs the division of a sub-list, I wanted to divide all of them and chain the result. The output should be like this, Output: [[[0, 10, 20], [30, 40, 50], [60, 70, 80], [90]], [[1, 11, 21], [ 31, 41, 51], [61, 71, 81], [91]], ...]

  • Pq def index must run on Buckets which is a list with 10 sub-lists

  • 1

    In this case I edited the reply @jusintique,

  • Victor, perfect! Thank you so much! But a doubt that arose applying this function would be possible to carry out this division with Dict through the Keys of the elements? Without wanting to abuse ...

  • 1

    Well, that would be another question, so please ask a new question here at Stackoverflow detailing the possible inputs and the desired outputs and if you want to share here the link. I am available!

  • Victor, before posting the new question, I was in the following question, how to use its function if foo = list(range(100))

  • Sorry for the delay in understanding why the function was not returning to its Output.

  • 1

    I don’t get it. Would you like to pass any amount by being not only 10 but 100 as well? If so, you can create a parameter in the index function and change the value 10 by the parameter name.

  • The question is only how to get the same result, but passing another parameter. In your example, the parameter passed was foo = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90], I wanted to pass foo = list(range(100)), and get exactly the same result

  • 1

    Right, for this you can use the step of the range function: foo = list(range(0, 100, 10)) .

  • 1

    Yes friend. It will increase from 10 to 10. That is, the list you will assign in foo will be [0, 10, 20, 30... up to 466550].

  • Yes, thank you very much! I even deleted the comment, because I had noticed. I just posted the other question, can you take a look? https://answall.com/questions/448631/divider-dicion%C3%a1rio-em-python

  • Come on, no problem! Come on.

Show 8 more comments

1

First let’s see how to do with a single list:

def split(lista, tamanho):
    return [lista[i:i + tamanho] for i in range(0, len(lista), tamanho)]

lista = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
print(split(lista, 3)) # [[0, 10, 20], [30, 40, 50], [60, 70, 80], [90]]

The idea to split into lists of size N is to take N in N (note the third parameter of range, he says we should jump from tamanho in tamanho, instead of jumping 1 in 1), and go picking up a sub-list containing N elements (lista[i:i + tamanho]).

Having this function, just apply it to each element of your Bucket:

nova_lista = [ split(b, 3) for b in buckets ]

Of course, if you want you can also do with a loop:

nova_lista = []
for b in buckets:
    nova_lista.append(split(b, 3))

Browser other questions tagged

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