1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonで三重ループと条件分岐を一行で記述したい

Posted at

#はじめに
たかしくん問題を実装してるときに出会った知見メモ。
pulpを使うときに多重のfor文を一文で記述する必要があり勉強しました。
まだまだ記述の力不足を感じます。。。

#メモ
##三重ループ

for x in range(4):
    for y in range(3):
        for z in range(2):
            print(x,y,z)
>>0 0 0
>>0 0 1
>>0 1 0
>>0 1 1
>>0 2 0
>>0 2 1 ...

[(x,y,z) for x in range(4) for y in range(3) for z in range(2)]
>>[(0, 0, 0),
>> (0, 0, 1),
>> (0, 1, 0),
>> (0, 1, 1),
>> (0, 2, 0),
>> (0, 2, 1), ...

##三重ループ+条件分岐1つ

for x in range(4):
    if x ==3:
        for y in range(3):
            for z in range(2):
                print(x,y,z)
>>3 0 0
>>3 0 1
>>3 1 0
>>3 1 1
>>3 2 0
>>3 2 1

[(x,y,z) for x in range(4) if x == 3 for y in range(3) for z in range(2)]
>>[(3, 0, 0), (3, 0, 1), (3, 1, 0), (3, 1, 1), (3, 2, 0), (3, 2, 1)]

##三重ループ+条件分岐2つ

for x in range(4):
    if x ==3:
        for y in range(3):
            for z in range(2):
                if z == 1:
                    print(x,y,z)
>>3 0 1
>>3 1 1
>>3 2 1

[(x,y,z) for x in range(4) if x == 3 for y in range(3) for z in range(2) if z == 1]
>>[(3, 0, 1), (3, 1, 1), (3, 2, 1)]

#さいごに
for文が回る順序がややこしいね

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?