0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

《アルゴリズムを学ぶ》1.リスト

Last updated at Posted at 2025-02-05

Overview

基本中の基本。リストの操作をまとめました。
1.リストの基本
2.リストの基本操作
3.リストの探索と並べ替え
4.効率的なリスト操作
5.典型問題を解いてみる

1. リストの基本

リストの定義

my_list = [1, 2, 3, 4, 5]

リストの要素アクセス(インデックスを使う)

my_list[0]  # 1
my_list[-1] # 5(最後の要素)

リストのスライス

my_list[1:4]  # [2, 3, 4](1番目から3番目の要素を取得)
my_list[:3]   # [1, 2, 3](最初から2番目まで)
my_list[::2]  # [1, 3, 5](2つおき)

2. リストの基本操作

リストの要素の追加

my_list.append(6)    # 末尾に追加
my_list.insert(2, 99) # 2番目の位置に99を挿入

リストの要素の削除

my_list.pop()        # 末尾の要素を削除
my_list.pop(2)       # 2番目の要素を削除
my_list.remove(99)   # 値が99の要素を削除

リストの更新

my_list[1] = 100  # 2番目の要素を100に変更

リストの結合

new_list = my_list + [7, 8, 9]  # 新しいリストを作る
my_list.extend([7, 8, 9])       # 既存のリストを拡張

3. リストの探索と並べ替え

リスト内の検索

print(3 in my_list)  # True(3が含まれるか)
print(my_list.index(3))  # 3の位置を取得

リストのソート

my_list.sort()        # 昇順ソート
my_list.sort(reverse=True)  # 降順ソート
sorted_list = sorted(my_list)  # 新しいソート済みリストを作る

4. 効率的なリスト操作

リスト内包表記

squares = [x**2 for x in range(10)]  # [0, 1, 4, ..., 81]
evens = [x for x in my_list if x % 2 == 0]  # 偶数のみ取得

リストの最大・最小・合計

max(my_list)  # 最大値
min(my_list)  # 最小値
sum(my_list)  # 合計

5. 典型問題を解いてみる

例題1: 入出力の練習

問題:2つの整数を入力し、それらの積が偶数なら「Even」、奇数なら「Odd」と出力する。

参考:ABC086A - Product

回答 
a, b = map(int, input().split())  # スペース区切りの整数入力
print("Even" if (a * b) % 2 == 0 else "Odd")

例題2: リストの合計

問題: 長さNの整数リストが与えられるので、すべての合計を求める。

参考:ABC087B - Coins

回答 
A = int(input())  # 500円の枚数
B = int(input())  # 100円の枚数
C = int(input())  # 50円の枚数
X = int(input())  # 作るべき金額

count = 0
for a in range(A + 1):
    for b in range(B + 1):
        for c in range(C + 1):
            if 500 * a + 100 * b + 50 * c == X:
                count += 1
print(count)

例題3: 特定の要素のカウント

問題: 3桁の0と1の文字列が与えられ、1の個数を数える。

参考:ABC081A - Placing Marbles

回答 
s = input()  # "101" のような文字列
print(s.count("1"))

例題4. リストの検索

問題: 身長X以上の人が何人いるかを数える。

参考:ABC142B - Roller Coaster

回答 
N, X = map(int, input().split())
H = list(map(int, input().split()))  # 身長リスト
print(len([h for h in H if h >= X]))  # X以上の人の数

例題5. リストの並び替え

問題: N枚のカードがあり、AliceとBobが交互にカードを取る。大きいカードから順にAliceが取る。AliceとBobの点数差を求める。

参考:ABC088B - Card Game for Two

回答 
N = int(input())
A = list(map(int, input().split()))  # カードのリスト

A.sort(reverse=True)  # 降順ソート
alice = sum(A[::2])  # 奇数番目(Aliceが取る)
bob = sum(A[1::2])  # 偶数番目(Bobが取る)

print(alice - bob)  # 点数差
0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?