セクション 1. 章 5
single
Pythonにおけるリストの変更:要素の更新と変更
メニューを表示するにはスワイプしてください
Python では、リストは**ミュータブル(可変)**であり、一度作成した後でも内容の変更、追加、削除が可能。ミュータブルな特性により、リストは柔軟に扱うことができ、動的なデータ管理に非常に強力なツールとなる。
「ミュータブル」とは?
ミュータブルとは、データ構造が新しいオブジェクトを作成せずに更新できることを意味する。例えば、既存の要素の値を変更したり、複数の要素を置き換えたり、同じリスト内で直接要素の削除や挿入を行うことができる。
訪問予定の都市リストがあり、計画が変更になった場合でも、リスト内の要素を簡単に更新や置換が可能。
123456789cities = ["Paris", "Tokyo", "New York", "Berlin", "Sydney"] # Replacing the third city cities[2] = "Rome" print(cities) # Output: ['Paris', 'Tokyo', 'Rome', 'Berlin', 'Sydney'] # Replacing the last two cities with new ones cities[-2:] = ["Dubai", "Cape Town"] print(cities) # Output: ['Paris', 'Tokyo', 'Rome', 'Dubai', 'Cape Town']
この例では:
- インデックス2の都市「New York」を「Rome」に置き換え;
- 負のインデックスを使い、最後の2都市(「Berlin」と「Sydney」)を「Dubai」と「Cape Town」に置き換え。
一度に複数の変更も可能。
123456cities = ["Paris", "Tokyo", "New York", "Berlin", "Sydney"] # Replacing multiple cities in the middle cities[1:3] = ["Seoul", "Bangkok", "Mumbai"] print(cities) # Output: ['Paris', 'Seoul', 'Bangkok', 'Mumbai', 'Berlin', 'Sydney']
ここでは、「Tokyo」と「New York」を「Seoul」、「Bangkok」、「Mumbai」の3都市に置き換えています。リストの可変性がデータ管理においてどれほど柔軟であるかを示しています。
12345678910# List of daily temperatures in degrees Celsius temperatures = [22, 25, 19, 23, 27] # Increasing the temperature on the second day by 2 degrees temperatures[1] = temperatures[1] + 2 print(temperatures) # Output: [22, 27, 19, 23, 27] # Setting the last day's temperature to 30 degrees directly temperatures[-1] = 30 print(temperatures) # Output: [22, 27, 19, 23, 30]
上記のコードは、インデックスを使用してリスト内の特定の要素を直接変更することで、数値データを更新する方法を示しています。
タスク
スワイプしてコーディングを開始
travel_wishlist リストがあります。
- すべての都市の推定費用を割引後の金額に更新してください。
- 費用(ネストされたリストの3番目の要素)に**20%**の割引を適用します。
- インデックスを使って要素を更新してください。
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 5
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください