Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Ta Bort Tupler i Python: Ta Bort Referenser till Tupler | Behärska Python-Tuple
Python Datastrukturer

book
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.

movies = ("Inception", "Interstellar", "Tenet", "Dunkirk", "Memento")

# Deleting the tuple
del movies

# Attempting to print the deleted tuple will raise an error
print(movies)
1234567
movies = ("Inception", "Interstellar", "Tenet", "Dunkirk", "Memento") # Deleting the tuple del movies # Attempting to print the deleted tuple will raise an error print(movies)
copy

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.

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)
12345678910111213
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)
copy
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 variabeln temp_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

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?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4
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

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt