Ta Bort Tupler i Python: Ta Bort Referenser till Tupler
En tuple i Python är oföränderlig, vilket betyder att när den väl har skapats kan du inte ändra, lägga till eller ta bort dess element. Du kan dock ta bort hela tuplen med hjälp av del
-satsen.
9
1
2
3
4
5
6
7
movies = ("Inception", "Interstellar", "Tenet", "Dunkirk", "Memento")
# Deleting the tuple
del movies
# Attempting to print the deleted tuple will raise an error
print(movies)
1234567movies = ("Inception", "Interstellar", "Tenet", "Dunkirk", "Memento") # Deleting the tuple del movies # Attempting to print the deleted tuple will raise an error print(movies)
Ta bort objekt
Notera
Eftersom tupler är oföränderliga kan du inte direkt ta bort objekt från dem. Du kan dock kringgå detta genom att konvertera tuplen till en lista, ändra listan och sedan konvertera den tillbaka till en tuple.
99
1
2
3
4
5
6
7
8
9
10
11
12
13
movies = ("Inception", "Interstellar", "Tenet", "Dunkirk", "Memento")
# Convert the tuple to a list
movies_list = list(movies)
# Remove specific items
movies_list.remove("Tenet")
movies_list.remove("Dunkirk")
# Convert the list back to a tuple
movies = tuple(movies_list)
print(movies)
12345678910111213movies = ("Inception", "Interstellar", "Tenet", "Dunkirk", "Memento") # Convert the tuple to a list movies_list = list(movies) # Remove specific items movies_list.remove("Tenet") movies_list.remove("Dunkirk") # Convert the list back to a tuple movies = tuple(movies_list) print(movies)
Uppgift
Swipe to start coding
Djurfimerna tilltalade inte publiken, förutom den animerade filmen "Finding Nemo"
.
- Konvertera tuplen
movie_poster
till en lista och tilldela den till variabelntemp_list
. - Ta bort elementen
"The Lion King"
och"Jurassic Park"
från listan. - Konvertera listan tillbaka till en tupl och tilldela värdet till variabeln
movie_poster
. - Ta bort listan
temp_list
.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
movie_poster = ('The Lion King', 'Jurassic Park', 'Finding Nemo', '2001: A Space Odyssey', 'Interstellar', 'Gravity', 'The Martian')
# Write your code here
temp_list = list(movie_poster)
temp_list.remove('The Lion King')
temp_list.remove('Jurassic Park')
movie_poster = tuple(temp_list)
del temp_list
# Testing
print("Updated movie poster:", movie_poster)
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 3. Kapitel 4
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
movie_poster = ('The Lion King', 'Jurassic Park', 'Finding Nemo', '2001: A Space Odyssey', 'Interstellar', 'Gravity', 'The Martian')
# Write your code here
temp_list = ___
temp_list___
temp_list___
movie_poster = ___
___
# Testing
print("Updated movie poster:", movie_poster)
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal