@ginichi (S U)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Python リストを立て並びでエクセル保存したい

初めて質問します。
リストを順番に縦に並べてエクセルに保存したいです。

import openpyxl
book = openpyxl.Workbook()
sheet = book.worksheets[0]
lst=[11,12,13,14,15]
for n in range (1,5):
for e in lst:
sheet.cell(row=n,column=1).value = e
book.save(r'C:\test.xlsx')

上の結果はこのように最後の値が並んでしまいますがなぜでしょうか?

15
15
15
15
15

0 likes

1Answer

何が起きているか分からないときは変数をプリントしてみる癖をつけましょう。

lst=[11,12,13,14,15]
for n in range (1,5):
    for e in lst:
        print(f"row={n} e={e}")
row=1 e=11
row=1 e=12
row=1 e=13
row=1 e=14
row=1 e=15
row=2 e=11
row=2 e=12
row=2 e=13
row=2 e=14
row=2 e=15
row=3 e=11
row=3 e=12
row=3 e=13
row=3 e=14
row=3 e=15
row=4 e=11
row=4 e=12
row=4 e=13
row=4 e=14
row=4 e=15

for ループが二重になっているため、同じ行の値を何度もセットしています。

for ループでリストの要素とインデックス番号を一緒に扱うなら enumerate(lst, start) を使うといいでしょう。

lst=[11,12,13,14,15]
for (n, e) in enumerate(lst, 1):
    print(f"row={n} e={e}")
row=1 e=11
row=2 e=12
row=3 e=13
row=4 e=14
row=5 e=15
0Like

Comments

  1. @ginichi

    Questioner

    配列のループ処理の確認にてこずっていました。
    2つの変数をprintして納得し、enumerate関数の使い方がわかり解決しました!
    アドバイスありがとうございます。

Your answer might help someone💌