Python リストを使った宮殿の在庫管理

PythonBeginner
オンラインで実践に進む

はじめに

この実験では、古代エジプトのファラオの宫殿を题材に Python のリストの世界を探求します。あなたは宫殿に保管されている品物を整理し管理する守护者の役割を演じます。あなたの任务は、Python のリストの基本を学び、新しく身につけた知识を使って宫殿の在库を管理することです。

リストの基本を理解する

このステップでは、宫殿に保管されている品物を表す Python のリストを作成し始めます。リストからアイテムを追加および削除し、特定の要素にアクセスする方法を学びます。

まず、~/project のパスにある list_basics.py という名前の Python スクリプトファイルを開きましょう。スクリプトファイルの中に、次のコードを書きます:

## list_basics.py

## Create a list of palace items
palace_inventory = ["gold statue", "jeweled crown", "antique vase"]

## Add a new item to the list
palace_inventory.append("precious gems")

## Remove an item from the list
palace_inventory.remove("jeweled crown")

## Access the first item in the list
first_item = palace_inventory[0]
print(first_item)

スクリプトを実行します:

python list_basics.py

端末には以下の情報が表示されるはずです:

gold statue

リストの操作とスライシング

このステップでは、スライシングやリスト要素の更新など、高度なリスト操作テクニックを学びます。

~/project のパスに新しいファイル list_manipulation.py を開き、次のコードを追加します:

## list_manipulation.py

## Create a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

## Slice the list to get a subset
subset = numbers[2:7]
print(subset)

## Update specific elements in the list
numbers[5] = 100
print(numbers)

スクリプトを実行します:

python list_manipulation.py

端末には以下の情報が表示されるはずです:

[3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 100, 7, 8, 9, 10]

まとめ

この実験では、古代エジプトの宫殿のシナリオを設定して Python のリストの概念を紹介しました。あなたは宫殿の在库管理を担当する守护者として行動し、学びに実践的で魅力的なコンテキストを提供しました。この実験を完了することで、Python のリストを作成、操作、アクセスするための基本的なスキルを身につけました。これらのスキルは、有望な Python プログラマーにとって不可欠なものです。