Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ タプル操作 | その他のデータ型
Python入門
セクション 4.  5
single

single

bookタプル操作

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

タプル自体は変更できませんが、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)
copy
タスク

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

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

前提

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

完了までの手順

  1. リスト shelf1_update をタプル shelf1_update_tuple変換します。
  2. shelf1_update_tuple を既存のタプル shelf1連結し、新しいタプル 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実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

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

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

セクション 4.  5
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt