0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

2. データ構造

  • リスト、タプル、辞書、セット
  • これらのデータ構造の操作方法

データ構造は、プログラミングにおいて非常に重要な概念です。Pythonには、主に以下の4つの基本的なデータ構造があります:リスト、タプル、辞書、セット。それぞれについて詳しく説明し、サンプルコードを交えて解説します。

1. リスト (List)

リストは、順序付けられた変更可能なデータ構造です。角括弧 [] で囲んで定義します。

# リストの作成
fruits = ['apple', 'banana', 'orange']

# 要素へのアクセス
print(fruits[0])  # apple

# 要素の追加
fruits.append('grape')
print(fruits)     # ['apple', 'banana', 'orange', 'grape']

# 要素の削除
removed_fruit = fruits.pop()
print(removed_fruit)  # grape
print(fruits)         # ['apple', 'banana', 'orange']

# リストのスライス
print(fruits[1:3])    # ['banana', 'orange']

# リストの長さ
print(len(fruits))    # 3

2. タプル (Tuple)

タプルは、順序付けられた変更不可能なデータ構造です。丸括弧 () で囲んで定義します。

# タプルの作成
coordinates = (10, 20)

# 要素へのアクセス
print(coordinates[0])  # 10

# タプルの分割
x, y = coordinates
print(x, y)            # 10 20

# タプルの結合
new_coordinates = coordinates + (30,)
print(new_coordinates)   # (10, 20, 30)

# タプルの要素数
print(len(coordinates))  # 2

3. 辞書 (Dictionary)

辞書は、キーと値のペアを持つ変更可能なデータ構造です。波括弧 {} で囲んで定義します。

# 辞書の作成
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 値へのアクセス
print(person['name'])  # Alice

# 新しいキーと値の追加
person['job'] = 'Engineer'
print(person)  # {'name': 'Alice', 'age': 30, 'city': 'New York', 'job': 'Engineer'}

# キーの存在確認
print('age' in person)  # True

# キーと値の取得
for key, value in person.items():
    print(f"{key}: {value}")

# キーの削除
del person['city']
print(person)  # {'name': 'Alice', 'age': 30, 'job': 'Engineer'}

4. セット (Set)

セットは、重複のない要素の集合を表す変更可能なデータ構造です。波括弧 {} または set() 関数を使って定義します。

# セットの作成
fruits = {'apple', 'banana', 'orange'}

# 要素の追加
fruits.add('grape')
print(fruits)  # {'orange', 'banana', 'apple', 'grape'}

# 要素の削除
fruits.remove('banana')
print(fruits)  # {'orange', 'apple', 'grape'}

# セット演算
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# 和集合
print(set1 | set2)  # {1, 2, 3, 4, 5, 6, 7, 8}

# 積集合
print(set1 & set2)  # {4, 5}

# 差集合
print(set1 - set2)  # {1, 2, 3}

5. これらのデータ構造の操作方法

これらのデータ構造は、それぞれ異なる特性と使用場面があります:

  • リストは順序付けられた要素の集合を扱う際に便利です。
  • タプルは変更不可能なデータを扱う際や、関数の複数の戻り値として使用されます。
  • 辞書はキーと値のペアを扱う際に便利で、高速なデータ検索が可能です。
  • セットは重複のないユニークな要素の集合を扱う際や、集合演算を行う際に便利です。

これらのデータ構造を適切に選択し、組み合わせることで、効率的なプログラムを書くことができます。各データ構造の特性を理解し、状況に応じて最適なものを選ぶことが重要です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?