ã辞書のキーと値を入れ替えをPythonでやってみた - 牌語備忘録 - pygoãã®ç¶ãã
éããã¾ã£ããèãã¦ãªãã£ã(´・Ïï½¥`)ã®ã§ãæè¿ãã¼ããã¦ã®timeitã¢ã¸ã¥ã¼ã«ã使ã£ã¦è¨æ¸¬ãã¦ã¿ãã
import timeit t= timeit.Timer(setup="dict_data = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}", stmt=""" def d_change_a(d): di = {} for k in d: di[d[k]] = k return dict(di) d_change_a(dict_data) """) print "A-1: ", t.timeit(number = 100000) t= timeit.Timer(setup="dict_data = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}", stmt=""" def d_change_a2(d): for k in d: d[d.pop(k)] = k return d d_change_a2(dict_data) """) print "A-2: ", t.timeit(number = 100000) t= timeit.Timer(setup="dict_data = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}", stmt="dict((lambda d:[(d[k], k) for k in d])(dict_data))") print "B : ", t.timeit(number = 100000) t= timeit.Timer(setup="dict_data = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}", stmt=""" def d_change_c(d): return dict([(d[k], k) for k in d]) d_change_c(dict_data) """) print "C : ", t.timeit(number = 100000) t= timeit.Timer(setup="dict_data = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}", stmt="dict((v, k) for k, v in dict_data.iteritems())") print "D : ", t.timeit(number = 100000)
åé·ãªã³ã¼ãã«ãªã£ã¡ãã£ã(||ï¾Ðï¾)
çµæ
A-1: 0.560142993927 A-2: 0.769951105118 B : 0.857019901276 C : 0.855353832245 D : 0.778590917587
ãããªæãã§ã
æå¤ã«ãA-1ãéãï¼ããåã£ã¦ãã®ãå¿é
(´・Ïï½¥`)