Pular para o conteúdo principal

Como dividir listas em Python: Exemplos básicos e métodos avançados

Aprenda a dividir listas Python com técnicas como slicing, compreensão de listas e itertools. Descubra quando usar cada método para um tratamento ideal dos dados.
· 11 min leer

Explore com IA

As listas Python são tipos de dados dinâmicos e mutáveis usados para armazenar itens ordenados. Dividir listas é uma tarefa comum em Python, essencial para manipular e analisar dados de forma eficiente. 

Você pode aprender mais sobre análise de dados fazendo o programa de carreira Analista de Dados com Python para aprimorar suas habilidades, que aborda os vários métodos para dividir listas em Python, incluindo exemplos práticos e melhores práticas. 

Dominar essas técnicas vai melhorar suas habilidades de programação, tornando seus scripts mais eficientes e fáceis de manter. Vamos começar.

A resposta rápida: Como dividir uma lista em Python

  • A maneira mais simples de dividir uma lista em Python é usando o operador de corte ( : ). Por exemplo, podemos dividir uma lista assim: split_list = my_list[:5], que divide a lista no quinto índice. 

  • O resto deste artigo fala sobre outras maneiras de dividir uma lista, como compreensões de lista, itertools, numpy e muito mais. Cada método tem vantagens únicas e é adequado para diferentes casos de uso, como veremos.

O jeito mais comum: dividir uma lista usando o corte

A divisão de lista em Python por índice é provavelmente a técnica mais comum de divisão de lista. O método slicing garante que a lista Python seja dividida em sublistas no índice especificado. Aqui vai um guia passo a passo sobre como implementar o slicing em Python.

  • Defina a lista: Digamos que você tem uma lista [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] e quer dividi-la em um índice específico n.
  • Identifique o Índice de Divisão: Diz o índice n onde você quer dividir a lista.
  • Criar a primeira fatia: No código abaixo, crie um first_slice o para conter elementos desde o início da lista até, mas não incluindo, o índice n.
  • Criar a segunda fatia: Defina second_slice para incluir todos os elementos do índice n até o final da lista.
# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Index where the list will be split
n = 4

# Slice the list from the beginning to the nth index (not inclusive)
first_slice = my_list[:n]

# Slice the list from the nth index to the end
second_slice = my_list[n:]

# Print the first slice of the list
print("First slice:", first_slice)

# Print the second slice of the list
print("Second slice:", second_slice)

# Expected output:
# First slice: [1, 2, 3, 4]
# Second slice: [5, 6, 7, 8, 9, 10]

Entendendo a divisão de listas em Python

Cortar listas em Python é quando você pega uma ou mais sublistas da lista principal. Quando você quiser dividir uma lista no Python, precisa entender a sintaxe de divisão para entender melhor a sublista correta. A sintaxe de divisão é slice[start:stop:step].

  1. Início indica o início do índice do corte.
  2. Stop indica o fim do índice do corte
  3. O passo mostra os intervalos entre os cortes (1 por padrão).
# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list from index 2 to 7 (index 2 inclusive, index 7 exclusive)
# This will include elements at index 2, 3, 4, 5, and 6
sublist = my_list[2:7]

# Print the sliced sublist
print(sublist) 

# Expected output: [3, 4, 5, 6, 7]

De acordo com o código acima, o corte começa do índice 2 ao índice 6, já que a sublista não inclui o índice 7.

Os benefícios da divisão de listas em Python na legibilidade e eficiência do código incluem:

  • Simplificando o gerenciamento de dados: Ao dividir os dados em partes fáceis de lidar, os cientistas de dados podem separar facilmente os dados de treinamento e teste no machine learning.
  • Aumentando a modularidade: Escrever funções com sublistas específicas melhora a modularidade do seu código.
  • Otimizando o desempenho: Usar pedaços menores da lista faz com que o processamento seja mais rápido do que usar listas inteiras.
  • Aumentando a eficiência da memória: O método cria blocos sem copiar os dados subjacentes, tornando-o eficiente em termos de memória.

Diferentes técnicas para dividir listas em Python

Tem vários jeitos de dividir uma lista no Python. Abaixo estão alguns exemplos comuns que um profissional de dados pode encontrar durante sua prática.

Usando o corte de lista

O corte de lista do Python usa o operador : para dividir a lista no índice. Esse método usa a técnica de indexação para especificar o início e o fim do corte.

As diferentes técnicas para cortar incluem o seguinte:

Corte de índice positivo

Esse método usa os valores positivos dos índices, começando da esquerda para a direita, para acessar os elementos da lista.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list from index 2 to 7 (index 2 inclusive, index 7 exclusive)
# This will include elements at index 2, 3, 4, 5, and 6
sublist = my_list[2:7]

# Print the sliced sublist
print(sublist) 

# Expected output: [3, 4, 5, 6, 7]

Corte de índice negativo

Esse método de divisão de lista do Python usa os valores negativos dos índices, começando pelo último elemento da lista, da direita para a esquerda.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list to get the last 5 elements
sublist = my_list[-5:]

# Print the sliced sublist containing the last 5 elements
print(sublist)

# Slice the list to get all elements except the last 3
sublist = my_list[:-3]

# Print the sliced sublist containing all but the last 3 elements
print(sublist)

# Expected output:
# [6, 7, 8, 9, 10]
# [1, 2, 3, 4, 5, 6, 7]

Usando o método passo a passo

Essa abordagem usa condições específicas para dividir a lista ao acessar diferentes elementos.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list to get every second element, starting from the beginning
sublist = my_list[::2]

# Print the sliced sublist containing every second element
print(sublist) 

# Slice the list to get every second element, starting from index 1
sublist = my_list[1::2]

# Print the sliced sublist containing every second element, starting from index 1
print(sublist) 

# Slice the list to get the elements in reverse order
sublist = my_list[::-1]

# Print the sliced sublist containing the elements in reverse order
print(sublist) 

# Expected output:
# [1, 3, 5, 7, 9]
# [2, 4, 6, 8, 10]
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Omitindo índices

Esse método divide a lista Python, devolvendo só os elementos necessários em uma lista.

# Define a list of integers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Slice the list from the start to index 5 (index 5 not inclusive)
sublist = my_list[:5]

# Print the sliced sublist containing elements from the start to index 4
print(sublist) 

# Slice the list from index 5 to the end
sublist = my_list[5:]

# Print the sliced sublist containing elements from index 5 to the end
print(sublist) 

# Slice the list to get the entire list
sublist = my_list[:]

# Print the sliced sublist containing the entire list
print(sublist) 

# Expected output:
# [1, 2, 3, 4, 5]
# [6, 7, 8, 9, 10]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Usando compreensões de lista

A compreensão de listas em Python permite dividir uma lista em partes com base nos valores da lista existente.

# Define a function to split a list into chunks of a specified size
def split_list(lst, chunk_size):
    # Use a list comprehension to create chunks
    # For each index 'i' in the range from 0 to the length of the list with step 'chunk_size'
    # Slice the list from index 'i' to 'i + chunk_size'
    return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Split the list into chunks of size 3 using the split_list function
chunks = split_list(my_list, 3)

# Print the resulting list of chunks
print(chunks)

# Expected output:
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]

n O código acima usa o Python para dividir a lista em trechos de três valores e criar uma nova lista com trechos de três valores.

Usando Itertools

A divisão de listas em Python usando itertools usa o módulo Python para transformar dados por meio de iteração.

# Import the islice function from the itertools module
from itertools import islice
# Define a function to yield chunks of a specified size from an iterable
def chunks(iterable, size):
    # Create an iterator from the input iterable
    iterator = iter(iterable)
    
    # Loop over the iterator, taking the first element in each iteration
    for first in iterator:
        # Yield a list consisting of the first element and the next 'size-1' elements from the iterator
        yield [first] + list(islice(iterator, size - 1))

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Convert the generator returned by the chunks function into a list of chunks
chunked_list = list(chunks(my_list, 3))

# Print the resulting list of chunks
print(chunked_list)

# Expected output:
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]

Usando numpy

A biblioteca numpy em Python é útil para dividir matrizes em sublistas. A função .array_split() permite divisões ao especificar o número de divisões.

# Import the numpy library and alias it as np
import numpy as np

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Use numpy's array_split function to split the list into 3 chunks
chunks = np.array_split(my_list, 3)

# Convert each chunk back to a regular list and print the resulting list of chunks
print([list(chunk) for chunk in chunks])

# Expected output:
# [[np.int32(1), np.int32(2), np.int32(3), np.int32(4), np.int32(5)], [np.int32(6), np.int32(7), np.int32(8), np.int32(9), np.int32(10)], [np.int32(11), np.int32(12), np.int32(13), np.int32(14), np.int32(15)]]

Dividindo listas em partes

A função Python a seguir também permite dividir uma lista em partes. Esses blocos podem ser personalizados dependendo do número que o usuário precisar.

# Define a function to split a list into chunks of a specified size
def split_into_chunks(lst, chunk_size):
    chunks = []  # Initialize an empty list to store chunks
    
    # Iterate over the list with a step of chunk_size
    for i in range(0, len(lst), chunk_size):
        # Slice the list from index 'i' to 'i + chunk_size' and append it to chunks
        chunks.append(lst[i:i + chunk_size])
    
    return chunks  # Return the list of chunks

# Define a list of integers from 1 to 16
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

# Split the list into chunks of size 4 using the split_into_chunks function
chunks = split_into_chunks(my_list, 4)

# Print the resulting list of chunks
print(chunks)

# Expected output:
# [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

Dividindo listas com base em condições

Quando você quiser dividir uma lista no Python, pode definir algumas regras/condições para a sublista. Esse método permite que você crie uma sublista que atenda a essas condições.

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# List comprehension to filter elements divisible by 3
div_3 = [x for x in my_list if x % 3 == 0]

# List comprehension to filter elements not divisible by 3
not_div_3 = [x for x in my_list if x % 3 != 0]

# Print the list of elements divisible by 3
print(div_3)

# Print the list of elements not divisible by 3
print(not_div_3)

# Expected output:
# [3, 6, 9, 12, 15]
# [1, 2, 4, 5, 7, 8, 10, 11, 13, 14]

Usando loops for

Os loops for também podem ser usados para dividir listas em Python com base em condições e por meio de iteração.

# Define a function to split a list into sub-lists of size n
def split_by_n(lst, n):
    # Use a list comprehension to create sub-lists
    # For each index 'i' in the range from 0 to the length of the list with step 'n'
    # Slice the list from index 'i' to 'i + n'
    return [lst[i:i + n] for i in range(0, len(lst), n)]

# Define a list of integers from 1 to 15
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Split the list into sub-lists of size 5 using the split_by_n function
sub_lists = split_by_n(my_list, 5)

# Print the resulting list of sub-lists
print(sub_lists) 

# Expected output:
# [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]