セクション 1. 章 21
single
タプル操作
メニューを表示するにはスワイプしてください
タプル自体は変更できませんが、Python ではタプルを作成および結合するための操作が用意されています。
作成
tuple() 関数は、イテラブルオブジェクト(文字列、セット、リストなど)からタプルを作成し、リストや他のイテラブルをタプルに変換することができます。
連結
+ 演算子を使うことで、2つ以上のタプルを新しいタプルとして結合でき、元のタプルを変更せずにデータを順番に組み合わせることが可能です。
ノート
タプルのメソッド(count() や index() など)を使用するには、リストのメソッドと同様にドット記法を使う必要があります。
タプルのコンストラクタ、連結、およびタプルメソッドを実際のアプリケーションでどのように活用できるかを見ていきます。
実例アプリケーション
過去3か月間にセール対象となった商品を格納したリストがあるとします。これらをタプルに変換し、タプルを連結し、四半期内で特定の商品が何回セール対象となったかを調べます。また、商品の**最初の出現位置(インデックス)**も特定する必要があります。
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)
タスク
スワイプしてコーディングを開始
タプルを使って食料品店の棚の内容を管理します。目的は、新しい商品で棚を更新し、基本的な分析を行いながら、データの完全性(タプルの不変性)を維持することです。
前提
- 現在棚にある商品を表す既存のタプル
shelf1 - 棚に追加する新しい商品が入ったリスト
shelf1_update
完了までの手順
- リスト
shelf1_updateをタプルに変換し、shelf1_update_tupleという名前で保存。 - 既存のタプル
shelf1_update_tupleとshelf1を連結し、新しいタプルshelf1_concatを作成。 - 文字列
"celery"がshelf1_concatに何回現れるかを数え、その数を変数celery_countに保存。 "celery"でshelf1_concatが最初に現れるインデックスを調べ、変数celery_indexに保存。
出力要件
次の形式で正確に出力してください:
Updated Shelf #1: <shelf1_concat>
Number of Celery: <celery_count>
Celery Index: <celery_index>
<shelf1_concat>には結果のタプルを入れてください。<celery_count>には"celery"の出現回数を入れてください。<celery_index>にはタプル内で最初に"celery"が現れるインデックスを入れてください。
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 21
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください