【Python基礎】リストとfor文の強力な関係|ループで一括処理

リストとforの強力な関係

リストとfor文の組み合わせは、Pythonで最もよく使うパターンの一つです。

1. リストの全要素に処理を適用

prices = [100, 250, 80, 320]
total = 0

for price in prices:
    total += price

print(f"合計:{total}円")
▶ 出力結果

合計:750円

2. 条件付きフィルタリング

scores = [45, 82, 67, 91, 38, 75]
passed = []

for score in scores:
    if score >= 60:
        passed.append(score)

print(f"合格者のスコア:{passed}")
▶ 出力結果

合格者のスコア:[82, 67, 91, 75]

3. リスト内包表記(簡潔な書き方)

forとリストを1行で書く「リスト内包表記」はPython特有のスッキリした書き方です。

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

# 通常のfor文版
doubles = []
for n in numbers:
    doubles.append(n * 2)
print(doubles)

# リスト内包表記版(同じ意味)
doubles2 = [n * 2 for n in numbers]
print(doubles2)
▶ 出力結果

[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
< 前の記事並べ替えと集計(sort, sum, max)
次の記事 >二次元リスト(多次元配列)の基本

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

上部へスクロール