Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ タプル操作 | セクション
データ分析のためのPython基礎
セクション 1.  21
single

single

bookタプル操作

メニューを表示するにはスワイプしてください

タプル自体は変更できませんが、Python ではタプルを作成および結合するための操作が用意されています。

作成

tuple() 関数は、イテラブルオブジェクト(文字列、セット、リストなど)からタプルを作成し、リストや他のイテラブルをタプルに変換することができます。

連結

+ 演算子を使うことで、2つ以上のタプルを新しいタプルとして結合でき、元のタプルを変更せずにデータを順番に組み合わせることが可能です。

Note
ノート

タプルのメソッド(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)
copy
タスク

スワイプしてコーディングを開始

タプルを使って食料品店の棚の内容を管理します。目的は、新しい商品で棚を更新し、基本的な分析を行いながら、データの完全性(タプルの不変性)を維持することです。

前提

  • 現在棚にある商品を表す既存のタプル shelf1
  • 棚に追加する新しい商品が入ったリスト shelf1_update

完了までの手順

  1. リスト shelf1_update をタプルに変換し、shelf1_update_tuple という名前で保存。
  2. 既存のタプル shelf1_update_tupleshelf1 を連結し、新しいタプル shelf1_concat を作成。
  3. 文字列 "celery"shelf1_concat に何回現れるかを数え、その数を変数 celery_count に保存。
  4. "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" が現れるインデックスを入れてください。

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  21
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt