LoginSignup
11
6

More than 5 years have passed since last update.

Pythonでx, yとかの2重ループをやめたい

Last updated at Posted at 2018-10-04

2重ループで二次元画像の画素を走査するときに以下のように書く。
しかし、ネストが深くなっていやだ。。。

x_list = list(range(10))
y_list = list(range(20))

for x in x_list:
    for y in y_list:
        pass

itertoolsを使ってやるとネストが深くならない。

import itertools

x_list = list(range(10))
y_list = list(range(20))
product = itertools.product(x_list, y_list)

for x, y in product:
    pass

速度比較

itertoolsを使うと遅くなる。悲しい😢

import itertools
import time

x_list = list(range(1000))
y_list = list(range(1000))

product = itertools.product(x_list, y_list)
start_time = time.time()
for x, y in product:
    pass
end_time = time.time()
print("%f[sec]" % (end_time-start_time))
# => 0.062474[sec]

start_time = time.time()
for x in x_list:
    for y in y_list:
        pass
end_time = time.time()
print("%f[sec]" % (end_time-start_time))
# => 0.015663[sec]

そもそも

Pythonでこんな重いループ回す書き方しないようにしようね!
NumPyとかつかっていい感じに行列として処理しようね!!

終わり!閉廷!…以上!皆解散!

11
6
1

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
11
6