Yabu.log

ITなどの雑記

Pythonざっくり復習

Deep Learningの本を買ったのでちょっとずつ進めています。 まずはPythonを復習します。

zen of python大事

>>> import this

四則演算等

いちいちpow()みたいなのがないのが楽だと思っている。

>>> # 足し算
... 1 + 4
5
>>> # 引き算
... 4 - 6
-2
>>> # 掛け算
... 3 * 3
9
>>> # べき乗
... 3 ** 3
27
>>> # 剰余
... 14 % 5
4
>>> # 除算
... 14 / 5
2.8
>>> # 余り切り捨て除算
... 14 // 5
2

データ型

>>> import math
>>> type(math.pi)
<class 'float'>
>>> type(12)
<class 'int'>
>>> type('string')
<class 'str'>
>>> type("string")
<class 'str'>
>>> # Pythonは動的片付け。演算の結果の型が自動で決まったり、変換されたり。
... x = 10
>>> print(x)
10
>>> type(x)
<class 'int'>
>>> x = x * math.pi
>>> print(x)
31.41592653589793
>>> type(x)
<class 'float'>

リスト

大括弧[]を使う

>>> list = [1,2,3,4,5]
>>> print(list)
[1, 2, 3, 4, 5]
>>> list[5] # 要素外にアクセス
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> list[4] #普通にアクセス
5
>>> list[4] = 999 #要素の変更
>>> list.append(6) #要素の追加
>>> print(list)
[1, 2, 3, 4, 999, 6]
>>> 

ディクショナリ

波括弧{}を使う

>>> numbers = {'one':1}
>>> numbers['one']
1
>>> numbers['two'] = 2
>>> print(numbers)
{'one': 1, 'two': 2}
>>> 

if文

>>> example = True
>>> if example:
...     print('マジ')
... else:
...     print('ガセ')
... 
マジ

for文

>>> a = [3,1,4]
>>> for i in a:
...     print(i)
... 
3
1
4

関数

>>> hello()
hello world
>>> a = hello()
hello world
>>> a = hello
>>> a()
hello world
>>> def funfun(fun):
...     fun()
... 
>>> funfun(a) # 高階関数
hello world

numpy

numpyは標準ライブラリではないので入れないと動かないので苦戦。 pythonやる時いつも環境設定に消耗するの僕だけですか? この辺り参考に。。。。

qiita.com

とりあえずpyenvで最新のanaccondaを入れることに成功したらimport numpyができるようになりました。

ndarray

  • pythonの組み込みと違い要素ごと(element-wise)の演算ができる
  • 組み込みのlistと+の動作が違う
    • listの場合は連結の動作
    • ndarrayでは要素ごとの加算になる
  • Numpy.arrayはスカラ値とも演算が可能。
    • これをブロードキャストという
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> x = np.array(a)
>>> y = np.array(b)
>>> 
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> x + y
array([5, 7, 9])
>>> 
>>> a * b # 定義されていない
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'list'
>>> x * y
array([ 4, 10, 18])

Numpy.arrayの多次元配列

>>> num =  np.array([[1,2],[3,4]])
>>> i = np.array([[1,0],[0,1]])
>>> num * i
array([[1, 0],
       [0, 4]])
  • 一次元の配列をベクトルと呼ぶ
  • 2次元の配列を行列と呼ぶ
  • ベクトルや配列を一般化したものをテンソルと呼ぶ