Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Acessando Elementos em um Conjunto: Iteração e Teste de Pertencimento | Conjunto
Estruturas de Dados em Python

book
Acessando Elementos em um Conjunto: Iteração e Teste de Pertencimento

Como os conjuntos são não ordenados, você não pode acessar seus elementos por índice como faria com uma lista ou tupla. No entanto, você pode:

  • Verificar a existência de um elemento usando a palavra-chave in;

  • Iterar pelos elementos usando um loop for.

Verificando a Existência com in

A palavra-chave in permite que você verifique se um elemento específico existe dentro de um conjunto:

# Define a set of favorite movies
movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"}

# Check if specific movies are in the set
is_inception_present = "Inception" in movies # True
is_avatar_present = "Avatar" in movies # False

# Print results
print(is_inception_present) # Output: True
print(is_avatar_present) # Output: False
12345678910
# Define a set of favorite movies movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"} # Check if specific movies are in the set is_inception_present = "Inception" in movies # True is_avatar_present = "Avatar" in movies # False # Print results print(is_inception_present) # Output: True print(is_avatar_present) # Output: False
copy

Neste exemplo, usamos a palavra-chave in para verificar se filmes específicos estão presentes no conjunto de movies e armazenar o resultado como um valor booleano nas variáveis is_inception_present e is_avatar_present.

Iterando por um Conjunto com um Loop for

Você pode iterar sobre um conjunto usando um loop for para processar cada elemento individualmente. Como os conjuntos são não ordenados, a ordem de iteração é imprevisível.

# Define a set of favorite movies
movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"}

# Iterate through the set and print each movie title
print("Movie collection:")
for movie in movies:
print(movie)
1234567
# Define a set of favorite movies movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"} # Iterate through the set and print each movie title print("Movie collection:") for movie in movies: print(movie)
copy

Cada elemento no conjunto é acessado uma vez durante a iteração. A ordem dos elementos na saída pode variar.

Tarefa

Swipe to start coding

Você tem um conjunto bastante grande dos movies mais populares.

  • Atribua um valor booleano à variável is_first_movie_present para verificar se o filme "The Green Mile" está no conjunto.
  • Atribua um valor booleano à variável is_second_movie_present para verificar se o filme "Titanic" está no conjunto.
  • Atribua um valor booleano à variável is_third_movie_present para verificar se o filme "Interstellar" está no conjunto.
  • Use a palavra-chave in para realizar esta tarefa.

Solução

movies = {'The Shawshank Redemption', 'The Godfather', 'The Dark Knight', 'Pulp Fiction', 'Forrest Gump', 'Inception', 'Fight Club', 'The Matrix', 'The Lord of the Rings: The Return of the King', 'Star Wars: Episode IV - A New Hope', 'The Empire Strikes Back', 'The Godfather: Part II', 'Goodfellas', 'The Dark Knight Rises', 'The Silence of the Lambs', 'Schindler\'s List', 'City of God', 'The Usual Suspects', 'Seven Samurai', 'The Lion King', 'The Departed', 'Interstellar', 'Gladiator', 'Terminator 2: Judgment Day', 'Back to the Future', 'Casablanca', 'The Prestige', 'The Green Mile', 'The Shining', 'The Intouchables', 'The Pianist', 'Léon: The Professional', 'The Lord of the Rings: The Fellowship of the Ring', 'Pulp Fiction', 'Whiplash', 'The Wolf of Wall Street', 'The Revenant', 'The Social Network', 'The Terminator', 'The Big Lebowski', 'Saving Private Ryan', 'A Clockwork Orange', 'The Grand Budapest Hotel', 'The Incredibles', '12 Angry Men', 'The Hunt', 'The Conjuring'}

# Write your code here
is_first_movie_present = "The Green Mile" in movies

is_second_movie_present = "Titanic" in movies

is_third_movie_present = "Interstellar" in movies

# Testing
print(f"Presence of movies in the set:\nThe Green Mile: {is_first_movie_present};\nTitanic: {is_second_movie_present};\nInterstellar: {is_third_movie_present}.")
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 4
single

single

movies = {'The Shawshank Redemption', 'The Godfather', 'The Dark Knight', 'Pulp Fiction', 'Forrest Gump', 'Inception', 'Fight Club', 'The Matrix', 'The Lord of the Rings: The Return of the King', 'Star Wars: Episode IV - A New Hope', 'The Empire Strikes Back', 'The Godfather: Part II', 'Goodfellas', 'The Dark Knight Rises', 'The Silence of the Lambs', 'Schindler\'s List', 'City of God', 'The Usual Suspects', 'Seven Samurai', 'The Lion King', 'The Departed', 'Interstellar', 'Gladiator', 'Terminator 2: Judgment Day', 'Back to the Future', 'Casablanca', 'The Prestige', 'The Green Mile', 'The Shining', 'The Intouchables', 'The Pianist', 'Léon: The Professional', 'The Lord of the Rings: The Fellowship of the Ring', 'Pulp Fiction', 'Whiplash', 'The Wolf of Wall Street', 'The Revenant', 'The Social Network', 'The Terminator', 'The Big Lebowski', 'Saving Private Ryan', 'A Clockwork Orange', 'The Grand Budapest Hotel', 'The Incredibles', '12 Angry Men', 'The Hunt', 'The Conjuring'}

# Write your code here
is_first_movie_present = ___

is_second_movie_present = ___

is_third_movie_present = ___

# Testing
print(f"Presence of movies in the set:\nThe Green Mile: {is_first_movie_present};\nTitanic: {is_second_movie_present};\nInterstellar: {is_third_movie_present}.")

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt