Оновлення Кортежів у Python
Щоб змінити значення в кортежі, ви можете використовувати техніку, схожу на ту, що використовується для видалення. Оскільки кортеж є незмінним, ви не можете безпосередньо змінювати його елементи без виникнення помилки.
9
1
2
3
movie_ratings = (8.8, 9.0, 7.5, 6.8)
# Attempting to modify a tuple directly
movie_ratings[1] = 8.9 # Output: Error: 'tuple' object does not support item assignment
123movie_ratings = (8.8, 9.0, 7.5, 6.8) # Attempting to modify a tuple directly movie_ratings[1] = 8.9 # Output: Error: 'tuple' object does not support item assignment
Однак, перетворивши кортеж на список, ви можете легко внести бажані зміни.
99
1
2
3
4
5
6
7
8
9
10
11
12
13
current_movies = ("Inception", "Interstellar", "Tenet", "Dunkirk")
# Step 1: Convert the tuple to a list
movies_list = list(current_movies)
# Step 2: Update the second and third movie titles
movies_list[1] = "Memento"
movies_list[2] = "The Prestige"
# Step 3: Convert the list back to a tuple
current_movies = tuple(movies_list)
print(current_movies)
12345678910111213current_movies = ("Inception", "Interstellar", "Tenet", "Dunkirk") # Step 1: Convert the tuple to a list movies_list = list(current_movies) # Step 2: Update the second and third movie titles movies_list[1] = "Memento" movies_list[2] = "The Prestige" # Step 3: Convert the list back to a tuple current_movies = tuple(movies_list) print(current_movies)
Завдання
Swipe to start coding
Вам надано новий кортеж, що містить жанри, під назвою movie_genres
.
- Перетворіть кортеж на список і присвойте його змінній
temp_list
. - Замініть елемент
"Drama"
на"Thriller"
. - Замініть елемент
"Horror"
на"Adventure"
. - Перетворіть список назад на кортеж і присвойте значення змінній
movie_genres
. - Видаліть тимчасовий список.
Рішення
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
movie_genres = ("Action", "Comedy", "Drama", "Horror", "Sci-Fi")
# Write your code here
temp_list = list(movie_genres)
temp_list[2] = "Thriller"
temp_list[3] = "Adventure"
movie_genres = tuple(temp_list)
del temp_list
# Testing
print("Updated genres:", movie_genres)
Все було зрозуміло?
Дякуємо за ваш відгук!
Секція 3. Розділ 5
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
movie_genres = ("Action", "Comedy", "Drama", "Horror", "Sci-Fi")
# Write your code here
temp_list = ___
temp_list[___] = "Thriller"
temp_list[___] = "Adventure"
movie_genres = ___
___
# Testing
print("Updated genres:", movie_genres)
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат