Skip to content

Instantly share code, notes, and snippets.

@externvoid
Last active August 31, 2018 23:35
Show Gist options
  • Select an option

  • Save externvoid/e027cf9450cd288a5ccf39e40810aa42 to your computer and use it in GitHub Desktop.

Select an option

Save externvoid/e027cf9450cd288a5ccf39e40810aa42 to your computer and use it in GitHub Desktop.
Pythonのミソ

ページ番号は、みんなのPython 第4版, 2017年01月05日初版1刷

文はブロックで構成され、ブロックはインデントで表現する。文はdef, class, if, while, forで始まる。 switch文は、if…in syntax, else syntax, if…== syntaxで代用する。

ar = [1, 2]
for e in ar:
  e # => 1, 2

# コメント
"""
 改行を含むコメント(docstring, pp. 150)
"""
'''
 これもdocstring
'''

mutableオブジェクト(pp. 160)

List, Dictionary, Set, ByteArray(mutable Str)

immutableオブジェクト

Str, Bytes, Tuple, Int, Float, FrozenSet

Sequence(Str, Bytes)

ar = [1, 2]
ar[0] # index access
ar[1:] # => [2], slice access
ar[0:1] # => [1]
ar[0:2] # => [1, 2]
len(ar) # 2
ar + [3] # => [1, 2, 3], cancatinatable

その他、count(), index()に応答でき、for文でloopを組める(pp. 160)

シーケンスに関する詳しい説明、イテレータ or イテレータ・オブジェクトって何? pp. 240

シーケンスは内部にイテレータを持ってる。取り出すにはiter関数を使う。

ar = [1, 2]
itr = iter(ar)
next(iter) # => 1
next(iter) # => 2

順に取り出すという処理、アルゴリズムは至る所にある。ファイルアクセス、データベース処理、Sequenceアクセスがそれである。ネットワークアクセスにより取得したバッファ内のデータ処理もそうである。 インデックスを使って要素をバラバラに取り出せれば便利だが、インデックスの作成にコストを要するので、シーケンスといったデータ構造が用いられる。 次のメソッドを実装すれば事足りるからである。

  1. 次を取り出す
  2. 終わったら知らせる

SwiftにはSequenceをチョットだけ便利にしたCollectionってのがある。 3. 前を取り出す ってのが実装されている。

yieldキーワードを使って関数定義すれば、イテレータオブジェクトを返すジェネレータ関数を作成できる。

暗黙の型変換がない、型を揃えるのがPython流

day = 24
date = str(day) + 'days'
int(date) # => ValueError: invalid literal
str = "100"
int(str) # => 100
float("20") # => 20.0

モジュールのimport

import matplotlib.pyplot as plt
from statistics import median # from statistics module, importing median function
# not work in python 2.x
from math import pi
pi 3 # => 3.14…

raw文字列、文字列の差し込み

str = "OK\n" # including escape sequence '\'
rawstr = r"OK\n" # => OK\\n
"{} is founder of python".format('Guido') # => Guido is founder of python

lambda式とリスト内包表記式

a = lambda x: x * 2
a(2) # => 4
def b(x):
  return x * 2
b(3) # => 6
```py
ar = [1, 2]
t = 10
sum([t - e]**2 for e in ar]) # 145, 81 + 64 = 145

classの定義

publicな属性、attribute x, yをinstance variableにもつclass A

class A:
  def __init__(self, x, y):
    self.x = x
    self.y = y
a = A(1, 2)
a.x # => 1
a.y # => 2

setter, getterをproperty関数を使って登録できる。

class B:
  def __init__(self):
    self.__x = 100
  def getx(self):
    return self.__x
  def setx(self, x):
    self.__x = x
  x = property(getx, setx)
b = B()
b.x # => 100
b.setx(200)
b.x # => 200
b._Prop__x # => 200

__init__とかは、Special Functionって事らしい。他にも色々あるってさ!

高階関数を定義できる

高階関数とは、引数にcallback、要するに関数をとる関数、関数を戻値にする関数ってこと! 高階関数を呼び出して関数を生成し、そこに引数を与えて実行するという手順をでコレータという仕組みで一発で行う事ができる。

def logger(func):
  def inner(*args):
    print("args =", args)
    return func(*arg)
  return inner
def accumulate(a, b):
  return a + b

newfunc = logger(accumulate)
print(accumulate(1, 2)) # args =(1, 2), 3

これが、簡潔に記述できる。

@logger
def accumulate(a, b):
  return a + b

print(accumulate(1, 2)) # args =(1, 2), 3

多重代入

a, b = 1, 2
(x, y) = 10, 20
ar, br = [1, 2], [3, 4]
(xr, yr) = ([10, 20], [30, 40])

t = (1, 2, 3)
p, q, r = t # tuple unpack
arr = [10, 20, 30]
l, m, n = ar # list(array) unpack

多重代入+tuple, list unpack

numpy(ナムパイ)

# 自動生成
np.arange(0, 4) # => array([0, 1, 2, 3]), start, end
np.linspace(2.0, 5.0, 4) # => array([ 2.,  3.,  4.,  5.]), start, end, div

a = [x **2 for x in xrange(10)]
a # =>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 要素積
ar, br = [1, 2], [3, 4]
ar * br # => can't multiply sequence
np.array(ar) * np.array(br) # => [3, 8], [a11 * b11, a12 * b12]

# 内積、行列積(学校で習うMatrixの積)
np.dot(np.array(ar), np.array(br)) # => 11
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1, 0], [0, 1]]) # unit matrix

np.dot(ma, mb ) # => [[1, 2], [3, 4]]

# 外積、直積
np.outer(ma, mb)
# => 
array([[1, 0, 0, 1],
       [2, 0, 0, 2],
       [3, 0, 0, 3],
       [4, 0, 0, 4]])

np.outer(ar, br)
# => 
array([[1, 2],
       [1, 2]])

# 形状変換
np.outer(ma, mb).reshape((2, -1)) # 2 x 8の行列へ変換、引数は、(2, -1) = (2, 8)
# =>
array([[1, 0, 0, 1, 2, 0, 0, 2],
       [3, 0, 0, 3, 4, 0, 0, 4]])

# 形状変換2
p = np.arange(12)
p # => array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
p.resize((3,4))
p
# =>
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
p = np.arange(12)
p.resize((3,3))
p
# =>
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

numpy slideshare

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment