Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ リストの変更 | Pythonリストの習得
Pythonデータ構造
セクション 1.  5
single

single

リストの変更

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

Python では、リストは**ミュータブル(可変)**であり、一度作成した後でも内容の変更、追加、削除が可能。ミュータブルな性質により、リストは柔軟性が高く、動的なデータ管理に強力なツールとなる。

「ミュータブル」とは?

ミュータブルとは、データ構造が新しいオブジェクトを作成せずに更新できることを意味する。例えば、既存の要素の値を変更したり、複数の要素を置き換えたり、同じリスト内で直接要素の削除や挿入も可能。

訪問予定の都市リストがあり、計画が変更になった場合でも、リスト内の項目を簡単に更新や置換ができる例:

123456789
cities = ["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']

この例では:

  1. インデックス2の都市「New York」が「Rome」に置き換えられている;
  2. 負のインデックスを使い、最後の2都市(「Berlin」と「Sydney」)を「Dubai」と「Cape Town」に置き換えている。

一度に複数の変更も可能:

123456
cities = ["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」が3つの都市「Seoul」、「Bangkok」、「Mumbai」に置き換えられています。リストの可変性がデータ管理においていかに柔軟であるかを示しています。

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%**の割引を適用します。
  • インデックスを使って要素を更新します。

解答

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

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

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

セクション 1.  5
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt