Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Acceder a los Elementos en un Conjunto: Iteración y Prueba de Pertenencia | Conjunto
Estructuras de Datos en Python

book
Acceder a los Elementos en un Conjunto: Iteración y Prueba de Pertenencia

Debido a que los conjuntos son desordenados, no puedes acceder a sus elementos por índice como lo harías con una lista o tupla. Sin embargo, puedes:

  • Verificar la existencia de un elemento usando la palabra clave in;

  • Iterar a través de los elementos usando un bucle for.

Verificando la Membresía con in

La palabra clave in te permite verificar si un elemento específico existe dentro de un 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

En este ejemplo, usamos la palabra clave in para verificar si ciertas películas están presentes en el conjunto movies y almacenamos el resultado como un valor booleano en las variables is_inception_present e is_avatar_present.

Iterando a través de un Conjunto con un Bucle for

Puedes iterar sobre un conjunto usando un bucle for para procesar cada elemento individualmente. Dado que los conjuntos son desordenados, el orden de iteración es impredecible.

# 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 en el conjunto se accede una vez durante la iteración. El orden de los elementos en la salida puede variar.

Tarea

Swipe to start coding

Se te da un conjunto bastante grande de las movies más populares.

  • Asigna un valor booleano a la variable is_first_movie_present para verificar si la película "The Green Mile" está en el conjunto.
  • Asigna un valor booleano a la variable is_second_movie_present para verificar si la película "Titanic" está en el conjunto.
  • Asigna un valor booleano a la variable is_third_movie_present para verificar si la película "Interstellar" está en el conjunto.
  • Usa la palabra clave in para lograr esta tarea.

Solución

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}.")
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
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}.")

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt