python tips

pythonのメモ

pythonの自分用メモ

この辺の書き方とかは極端に可読性下がったりするのであんまり使わなかったりもするけど、覚えておきたいことがたまにあるのねん

2つのdictを1つのdictにまとめる

a = {'a': 1, 'b':2}
b = {'c': 1, 'd':2}

z = {**a, **b}

print(z)

####
{'a': 1, 'b': 2, 'c': 1, 'd': 2}

dictの値のソート

s = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

print(sorted(s.items(), key=lambda x: x[1]))

####
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

timeitを使った速度の計測

import timeit

print(timeit.timeit('"-".join(map(str, range(100)))', number=10000))

####
0.24178834100000002

変数のスワップ

a = 12 
b = 34

a, b = b, a

print(a)
print(b)

####
34
12

isと==

isは同じオブジェクトを指していればTrueになる == は参照している値が同じならtrueになる

a = [1, 2, 3]
b = a
c=list(a)


print(a is b)
print(a == b)

print(a==c)
print(a is c)

####
True
True
True
False

pythonのbuildin http server

$ python3 -m http.server

list生成の際のコード簡約化

even_squares = []
for x in range(10):
    if not x % 2:
        even_squares.append(x * x)

これが等価

 even_squares = [x * x for x in range(10) if not x % 2]
 print(even_squares)

###
[0, 4, 16, 36, 64]
connvoi's Picture

About connvoi

肉とビールと料理と写真とゲーム たまに技術 python / Solr / PHP / ansible

アマゾンセール情報サイト アマセール管理人

Jp, Tokyo https://connvoi.com