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?

問題

  • 以下のリストを生成せよ
    • [1, 2, 4, 8, 16, ..., 256]
    • [2^n | n: 0 <= n <= 8を満たす整数]と同義

for 文を用いたアプローチ

  • 空リストを用意

    l = []
    

  • for 文の中で2^nを追加していく

    for i in range(9):
        l.append(2**i)
    print(l)
    

  • 実行結果

    [1, 2, 4, 8, 16, 32, 64, 128, 256]
    

リスト内包表記を用いたアプローチ

  • リスト内包表記:数学の集合の内包表記のような表現

  • まさに問題で定義した[2^n | n: 0 <= n <= 8を満たす整数]のような表現

    • [要素を表す式 繰り返しの条件]の形式でリストを生成する
  • 以下のように1行で生成できる

    l = [2**i for i in range(9)]
    print(l)
    

  • 実行結果

    [1, 2, 4, 8, 16, 32, 64, 128, 256]
    
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?