Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Operazioni sulle Tuple | Altri Tipi di Dati
Introduzione a Python

book
Operazioni sulle Tuple

Sebbene le tuple non possano essere modificate, Python offre operazioni per crearle e combinarle in modo efficace.

Creazione

La funzione tuple() crea una tupla a partire da un oggetto iterabile (stringhe, set, liste), consentendo la conversione di liste o altri iterabili in tuple.

Concatenazione

È possibile unire due o più tuple in una nuova tupla utilizzando l'operatore +, permettendo di combinare i dati in sequenza senza modificare le tuple originali.

Nota

Ricorda che, per utilizzare i metodi delle tuple, come count() e index(), è necessario utilizzare la dot notation, proprio come fatto con i metodi delle liste.

Esploriamo come utilizzare il costruttore di tuple, la concatenazione e i metodi delle tuple in un'applicazione pratica.

Applicazione di esempio

Immagina di avere delle liste che memorizzano gli articoli messi in vendita negli ultimi 3 mesi. È necessario convertirle in tuple, concatenare le tuple e poi determinare quante volte un articolo è stato messo in vendita nell'ultimo trimestre. Occorre inoltre determinare la posizione dell'indice per individuare la prima occorrenza di un articolo.

# Define lists with items that have been put on sale, recording each sale occurrence for different months
janSales_list = ["apples", "oranges", "apples"]
febSales_list = ["bananas", "oranges", "bananas"]
marSales_list = ["apples", "bananas", "apples"]

# Convert the lists to tuples to ensure immutability (unchangeable)
janSales = tuple(janSales_list)
febSales = tuple(febSales_list)
marSales = tuple(marSales_list)

# Concatenate all monthly sales into a single tuple for the quarter
quarterlySales = janSales + febSales + marSales
print("Consolidated quarterly sales:", quarterlySales)

# Use the `count()` method to determine how many times "apples" have been on sale during the quarter
apples_sale_count = quarterlySales.count("apples")
print("Apples have been on sale:", apples_sale_count, "times.")

# Use the `index()` method to find the first occurrence of "apples" in the quarterly sales
first_apple_sale_index = quarterlySales.index("apples")
print("The first sale of apples this quarter was at index:", first_apple_sale_index)
123456789101112131415161718192021
# Define lists with items that have been put on sale, recording each sale occurrence for different months janSales_list = ["apples", "oranges", "apples"] febSales_list = ["bananas", "oranges", "bananas"] marSales_list = ["apples", "bananas", "apples"] # Convert the lists to tuples to ensure immutability (unchangeable) janSales = tuple(janSales_list) febSales = tuple(febSales_list) marSales = tuple(marSales_list) # Concatenate all monthly sales into a single tuple for the quarter quarterlySales = janSales + febSales + marSales print("Consolidated quarterly sales:", quarterlySales) # Use the `count()` method to determine how many times "apples" have been on sale during the quarter apples_sale_count = quarterlySales.count("apples") print("Apples have been on sale:", apples_sale_count, "times.") # Use the `index()` method to find the first occurrence of "apples" in the quarterly sales first_apple_sale_index = quarterlySales.index("apples") print("The first sale of apples this quarter was at index:", first_apple_sale_index)
copy
Compito

Swipe to start coding

Gestione del contenuto di uno scaffale di negozio di alimentari utilizzando tuple, garantendo l'integrità dei dati ed eseguendo alcune verifiche analitiche.

  • Convertire la lista shelf1_update dei nuovi articoli in una tupla chiamata shelf1_update_tuple.
  • Concatenare shelf1_update_tuple con la tupla esistente shelf1 per creare una nuova tupla shelf1_concat.
  • Contare quante volte "celery" appare in shelf1_concat e memorizzare il risultato in celery_count.
  • Trovare l'indice della prima occorrenza di "celery" in shelf1_concat e memorizzarlo in celery_index.

Requisiti di output

  • Stampare il contenuto aggiornato dello scaffale: "Updated Shelf #1: <$shelf1_concat>".
  • Stampare il numero di "celery": "Number of Celery: <$celery_count>".
  • Stampare l'indice della prima occorrenza di "celery": "Celery Index: <$celery_index>".

Soluzione

# Initial items on shelf #1 (provided as a tuple)
shelf1 = ("celery", "spinach", "cucumbers")

# Items being added to the shelf #1 (provided as a list)
shelf1_update = ["tomatoes", "celery", "cilantro"]

# Task 1: Convert the list of new shelf items to a tuple
shelf1_update_tuple = tuple(shelf1_update)

# Task 2: Concatenate the new tuple with the existing tuple
shelf1_concat = shelf1 + shelf1_update_tuple
print("Updated Shelf #1:", shelf1_concat)

# Task 3: Count the number of "celery" in the updated tuple
celery_count = shelf1_concat.count("celery")
print("Number of Celery:", celery_count)

# Task 4: Find the index of "celery" in the updated tuple
celery_index = shelf1_concat.index("celery")
print("Celery Index:", celery_index)
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 5
# Initial items on shelf #1 (provided as a tuple)
shelf1 = ("celery", "spinach", "cucumbers")

# Items being added to the shelf #1 (provided as a list)
shelf1_update = ["tomatoes", "celery", "cilantro"]

Chieda ad AI

expand
ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt