セクション 4. 章 5
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"が現れるインデックスを入れてください。
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 5
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください