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?

Pythonで詳細情報をグループ化してファイルに出力したい

Last updated at Posted at 2025-09-30

今回のサンプルでは、悪魔配列(devil_details)を強さ別にグループ化する。
悪魔配列の詳しい内容は今回割愛しています。

詳細データをグループ化
from datetime import datetime

POWER_MAP = {
    # DEVIL_ID : "POWER"
    "00" : "最強",
    "01" : "強い",
    "02" : "普通",
    "03" : "弱い",
    "04" : "最弱"
}

timestamp   = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = f"output_{timestamp}.txt"
# 詳細データの結果を入れる
# 例: { ID:[other1, other2, ...], ID:[other1], ... }
results = {v: [] for v in POWER_MAP.keys()}

# devil_details : 悪魔の詳細情報が入った配列
for devil_detail in devil_details:

    # 詳細情報各々取得
    name = devil_detail.get("name")
    # devil_id = ...
    # personallity = ...
    # features = ...
    # others = ...

    lines = []
    lines.append(f"NAME: {name}")
    lines.append(f"DEVIL_ID: {devil_id}")
    lines.append(f"PERSONALLITY: {personallity}")
    lines.append(f"FEATURES: {features}")

    for index, other in enumerate(others, 1):
        # ナンバー右詰め
        lines.append(f"[{str(index).rjust(2)}]{other}")
    # 強さごとにグループ分け
    results[devil_id].append("\n".join(lines))

# ファイルに出力
with open(output_file, "w", encoding="utf-8") as out:
    for _id, _power in POWER_MAP.items():
        out.write(f"== {_power} ==")
        # グループ分けした結果を書き込む
        for block in results.get(_id, []):
            out.write(f"\n{block}")
出力結果
== 最強 ==
NAME: 銃の悪魔
DEVIL_ID: 00
PERSONALLITY: 無慈悲
FEATURES: 作中最強クラス
[ 1] 根源的恐怖に近い存在
[ 2] 数十秒の顕現で被害甚大
[ 3] 銃の欠片で他の悪魔パワーアップ
...

NAME: ...
DEVIL_ID: 00
PERSONALLITY: ...
FEATURES:...
...

== 強い ==
...
...

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?