How to simplify this code in Python?

Asked

Viewed 151 times

0

I am learning Python and I came across an exercise that called for the creation of a group() function that would divide the elements of a list into smaller lists according to predetermined size, according to the two examples below:

group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) would result in [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4) would result in [[1, 2, 3, 4], [5, 6, 7, 8], [9]]

I was able to solve the problem, but I am looking for simpler and more elaborate options than mine, which did not seem good. Could someone please help me? The code I was able to create was as follows::

    def group(lista, a):
b = []
x = 0
if len(lista) % a == 0:
    for i in range(int(len(lista)/a)):
        b.append([])
    for c in range(len(b)):
        for i in range(a):
            b[c].append(lista[x])
            x += 1
else:
    for i in range(int(len(lista) / a + 1)):
        b.append([])
    for c in range(int(len(b)-1)):
        for i in range(a):
            b[c].append(lista[x])
            x += 1
    for c in range(0, 1):
        for i in range(int(len(lista) % a)):
            b[-1].append(lista[x])
            x += 1
return b

2 answers

4

Your code will be simpler using List Comprehension:

def group(lista, a):
  return [list(lista[i:i+a]) for i in range(0, len(lista), a)]

print(group(range(0,100),4))

Test the code on Repl.it

Upshot:

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], 
 [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35], 
 [36, 37, 38, 39], [40, 41, 42, 43], [44, 45, 46, 47], [48, 49, 50, 51], 
 [52, 53, 54, 55], [56, 57, 58, 59], [60, 61, 62, 63], [64, 65, 66, 67], 
 [68, 69, 70, 71], [72, 73, 74, 75], [76, 77, 78, 79], [80, 81, 82, 83], 
 [84, 85, 86, 87], [88, 89, 90, 91], [92, 93, 94, 95], [96, 97, 98, 99]]

The idea is to i traverse the indexes of lista bouncing a and then for each variation of i a slice of lista going from the index i up to the index i+a.

0

From what I understand you want to implement an algorithm that is able to split a list into N sublists. To solve this question we can use the following algorithm:


def group(lis, n):
    return [list(lis[i:i + n]) for i in range(0, len(lis), n)]


# Montando a lista:
lista = list(map(int, input('Digite todos os valores: ').split()))

while True:
    try:
        num = int(input(f'Desejas dividir a lista em quantas sublistas? '))
        if num < 1:
            print('\033[31mValor INVÁLIDO! Digite valores maiores que "0"!\033[m')
        else:
            break
    except ValueError:
        print('\033[31mValor INVÁLIDO! Digite apenas valores inteiros!\033[m')

print(f'\033[32mA lista de sublistas gerada foi:\n{group(lista, num)}')

This algorithm is more generic. Yeah, it might work with any lists.

When we run this algorithm we receive the following message: Digite todos o valores da lista: . Right now we must type all the values of the list in the same line, separated for a single space and press enter.

After typed terms all values the list will be mounted.

Then we received the second message: Em quantas sublistas desejas dividir a lista: . Right now we must enter the amount of sublists we wish to form.

From that moment on, both the lista how much the amount of sublists are passed as arguments to the function group. Once there, the list is subdivided by the quantity previously reported.

Subsequently the list containing the N sublists is displayed.

Browser other questions tagged

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