2
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?

More than 1 year has passed since last update.

print内でifを使う

Last updated at Posted at 2023-08-08

配列の中に、指定の要素があるかどうか出力をしたかったが、ごちゃごちゃしたくなくて試してみた。

0-0.書いてみる

i = [[0,0],[0,1]]

x = [0,0]
y = [1,1]

print("xあるよ" if x in i else "xないよ")
print("yあるよ" if y in i else "yないよ")

0-1.実行結果

xあるよ
yないよ

まとめ

すぐに忘れちゃうから、忘れない脳みそが欲しい。

1-0.検索時間

リスト、タプル、辞書型で検索時間に差が・・・

import time

list_ = [x for x in range(100000)]
ans = 99999
time_s = time.time()
print("xあるよ" if ans in list_ else "xないよ")
time_e = time.time()
print(time_e - time_s)

tuple_ = tuple([x for x in range(100000)])
ans = 99999
time_s = time.time()
print("xあるよ" if ans in tuple_ else "xないよ")
time_e = time.time()
print(time_e - time_s)

dict_ = {x for x in range(100000)}
ans = 99999
time_s = time.time()
print("xあるよ" if ans in dict_ else "xないよ")
time_e = time.time()
print(time_e - time_s)

1-1.実行結果

xあるよ
0.0013227462768554688
xあるよ
0.0011975765228271484
xあるよ
5.4836273193359375e-06

検索スピードは辞書型が圧倒的早さ。

2-0.おまけ

リスト、タプル、辞書作成からタイム計測

import time


time_s = time.time()
list_ = [x for x in range(100000)]
ans = 99999
print("xあるよ" if ans in list_ else "xないよ")
time_e = time.time()
print(time_e - time_s)


time_s = time.time()
tuple_ = tuple([x for x in range(100000)])
ans = 99999
print("xあるよ" if ans in tuple_ else "xないよ")
time_e = time.time()
print(time_e - time_s)


time_s = time.time()
dict_ = {x for x in range(100000)}
ans = 99999
print("xあるよ" if ans in dict_ else "xないよ")
time_e = time.time()
print(time_e - time_s)

2-1.実行結果

xあるよ
0.006294727325439453
xあるよ
0.006987571716308594
xあるよ
0.009082317352294922

作るところからなら辞書が遅いんかい

2
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
2
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?