Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Доступ до Елементів у Множині: Ітерація та Перевірка Членства | Множина
Структури даних Python

book
Доступ до Елементів у Множині: Ітерація та Перевірка Членства

Оскільки множини є невпорядкованими, ви не можете отримати доступ до їх елементів за індексом, як це робите зі списком або кортежем. Однак, ви можете:

  • Перевірити наявність елемента за допомогою ключового слова in;

  • Ітерувати через елементи за допомогою циклу for.

Перевірка членства з in

Ключове слово in дозволяє перевірити, чи існує конкретний елемент у множині:

# 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

У цьому прикладі ми використовуємо ключове слово in, щоб перевірити, чи є конкретні фільми у множині movies, і зберегти результат як логічне значення в змінних is_inception_present та is_avatar_present.

Ітерація через множину за допомогою циклу for

Ви можете ітерувати через множину за допомогою циклу for, щоб обробити кожен елемент окремо. Оскільки множини є невпорядкованими, порядок ітерації є непередбачуваним.

# 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

Кожен елемент у наборі доступний один раз під час ітерації. Порядок елементів у виведенні може змінюватися.

Завдання

Swipe to start coding

Вам надано досить великий набір найпопулярніших movies.

  • Призначте булеве значення змінній is_first_movie_present, щоб перевірити, чи є фільм "The Green Mile" у наборі.
  • Призначте булеве значення змінній is_second_movie_present, щоб перевірити, чи є фільм "Titanic" у наборі.
  • Призначте булеве значення змінній is_third_movie_present, щоб перевірити, чи є фільм "Interstellar" у наборі.
  • Використовуйте ключове слово in для виконання цього завдання.

Рішення

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}.")
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 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}.")

Запитати АІ

expand
ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

some-alt