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

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

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

セクション 4.  5
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt