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の内包表記でつまづきそうになったから記録する

0
Last updated at Posted at 2026-08-09

この記事はPythonのリスト内包表記につまづきかけた件

プログラミング初学者の転びかけ同志の参考や未来の自分の助けになることを祈る。

  • きっかけ
    以下の内包表記により二重リストを作成する記法の勉強している際に頭が混乱

標準入力は以下とする。
3
1, 2, 3
4, 5, 6
7, 8, 9

n=int(input())
li = [[int(x) for x in input().split()] for _ in range (n)]

ポイント

これを理解するには二つの部分に分解して考えると良い。

  • [int(x) for x in input().split()] 部分 = 標準入力を1行ずつ受け取る
    これは単純な内包表記だ。念の為確認すると。
    A:リストの要素となる値(作成するリストへの入力)
    B:Cの各要素を受け取る変数(イテラブルと作成するリストの橋渡し)
    C:イテラブル
li = [A for B in C]

これは標準入力を1行ずつ処理していることに他ならない。
3
1, 2, 3 //1回目この行を処理//
4, 5, 6 //2回目この行を処理//
7, 8, 9 //3回目この行を処理//

  • [[A] for _ in range(n)] 部分
    これは事前に与えられた行情報から、1回目、2回目、3回目の部分を機械的に制御しているだけである。

まとめ

恥を忍んでこのような記事を書いたが、二重リストを作る都合上、角括弧が重なり混乱したが機械的に考えると単純だった。

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?