Python

in  

Pythonの雑多なメモです。

type関数で型を表示する。

1
2
3
4
5
print(type((1,)))
print(type([1]))
print(type({1: '1'}))
print(type(range(1)))
print(type('hoge'))
1
2
3
4
5
<class 'tuple'>
<class 'list'>
<class 'dict'>
<class 'range'>
<class 'str'>

List

同じ値が詰まったリストを返す

1
print(['-1'] * 3)
1
['-1', '-1', '-1']

sys

プログラムを終了させる

1
2
3
4
import sys
sys.exit()
# 'hoge'は出力されずに終了する
print('hoge')

module

https://qiita.com/suzuki-hoge/items/f951d56290617df4279e https://qiita.com/sukobuto/items/15c1173b3f37f0306dd5 http://note.crohaco.net/2014/python-module/

空リスト判定

1
2
3
4
5
lis = []
if lis:
   return 'not empty'
else:
   return 'empty'
1
empty

ファイル操作

1
2
3
4
5

import os

// ファイルディレクトリ一覧
os.listdir('/path/to/dir')

withを使えば自動でcloseしてくれる

1
2
with open(file_path) as f:
    lines = f.readlines()

python doc

http://azunobu.hatenablog.com/entry/2015/05/02/080000

help関数で出力されるドキュメンテーションの書き方。 下記のように記載する。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13

def binary_search(lis, val):
    u""" 引数で与えられたListの中から検索valの位置を検索して返す。
    検索値が存在しない場合は-1を返す
    """

    length = len(lis)
    if length == 0:
	return -1

    mid = math.floor(length / 2)

    return _search_array(lis, val, mid, 0, length - 1)

インクリメント

1
2
3
4
count = 1
while count <= 100:
    print(count)
    count += 1

小数点の切り上げ、切り捨て

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11

import math

# 切り捨て
math.floor(x)

# 切り上げ
math.ceil(x)

# 中間(0.5)の場合は偶数に丸められる
round(x)

例外

例外の投げ方

1
raise Exception("I know python!")

Unittest

1
2
with self.assertRaises(Exception):
    reverse('hoge')

クラス

https://qiita.com/Usek/items/a206b8e49c02f756d636

Pythonではメソッドは最低1つの引数を持ちます。この最初の引数は必ずselfという名前にする慣例があります。

1
2
3
4
class Spam:
    val = 100
    def ham(self):
	self.egg('call method')

コンストラクタは__init__() デストラクタは__del__

クラスチェック oがstrクラスまたはそのサブクラスかをチェック

1
if isinstance(o, str):

strクラスであることをチェック

1
if type(o) is str:

標準入出力

1
2
3
4
5
6
for line in sys.stdin:
    lis = line.replace('\n', '').split(',')
    if score.header == None:
	score.header = lis
    elif lis != '':
	score.score.append(lis)

文字列

1
2
3
4
str = 'test'
# 小文字判定
if str.islower():
    return 'lower case'
1
lower case
1
2
3
4
str = 'TEST'
# 大文字判定
if str.isupper():
    return 'upper case'
1
upper case
1
2
3
4
str = '123'
# 数字判定
if str.isdigit():
    return 'degit'
1
degit

stringsからbyteへ

1
2
3

b = 'あ'.encode('utf-8')
return b
1
b'\xe3\x81\x82'

byteからstringsへ

1
2
3
b = b'\xe3\x81\x82'

return b.decode('utf-8')
1

bを接頭辞とした文字列はbyte

文字列を表すのにbytes(バイナリデータを含む)とstr(Unicode文字を含む)の2種類がある。 bytesの場合、下記のように先頭にbをつける

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# str
print('hoge')

# bytes
print(b'hoge')

# bytes->str
print(b'hoge'.decode())

# str->bytes
print('hoge'.encode())
1
2
3
4
hoge
b'hoge'
hoge
b'hoge'

文字列が含まれるか?

1
2
3
4
5
# 含まれる場合は True
print('ho' in 'hoge')

# 含まれない場合は False
print('fu' in 'hoge')
1
2
True
False

1
2
# 無限
return float('inf')
1
inf

高階関数

reduce

1
2
3
import functools

return functools.reduce(lambda x, y: x + y, range(1, 5))
1
10

if

https://www.tutorialspoint.com/python/python%5Fif%5Felse.htm

1
2
3
4
5
6
7

if condition:
     ...
elif confition:
    ....
else:
    ....

条件のand,or条件

1
2
3
4
5
6
7

if condition1 and condition2:
     ...
elif condition1 or condition2:
    ....
else:
    ....

NoneはFalse扱い

1
2
3
4
if None:
    print('If block')
else:
    print('Else block')
1
Else block

0はFalse扱い

1
2
3
4
if 0:
    print('If block')
else:
    print('Else block')
1
Else block

1はTrue扱い

1
2
3
4
if 1:
    print('If block')
else:
    print('Else block')
1
If block

空文字はFalse扱い

1
2
3
4
if '':
    print('If block')
else:
    print('Else block')
1
Else block

リスト内包表記

1
2
3
4
5
6
7
8
9

print([i for i in range(10)])
lis =[1, 2, 3, 4, 5, 6, 7, 8, 9]
print([ x**2 for x in lis])
print([ x**2 for x in lis if x % 2 == 0])

# 実行順序は左から右
matrix = [[ 1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([x for row in matrix for x in row])
1
2
3
4
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[4, 16, 36, 64]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

generator

内包表記における遅延評価

1
2
3
4
matrix = [[ 1, 2, 3], [4, 5, 6], [7, 8, 9]]
gen = (x for row in matrix for x in row)
print (next(gen))
print (next(gen))
1
2
1
2

closure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def test(val):
    print(val)
    # closureは関数の外の変数(val)にアクセスできる
    def inner1():
	print(val)
    inner1()
    val = 'hoge'
    inner1()

    # valの値を変更しても外のスコープには影響しない
    def inner2():
	val = 'woo'
	print(val)
    inner2()
    print(val)

    # nonlocalを使って外のスコープの値を変更する
    def inner3():
	nonlocal val
	val = 'woo'
	print(val)
    inner3()
    print(val)

test('fuga')
1
2
3
4
5
6
7
fuga
fuga
hoge
woo
hoge
woo
woo

list tuple

listとtupleの違い http://d.hatena.ne.jp/r%5Fikeda/20111111/listtuple

  • リストは変更可能だがタプルは変更不可能
  • タプルはマップのキーにできる

slice

list[start:end] end番目の要素は含まれない。

負の数を使うと末尾からの計算が楽になり、いちいちlenを使わなくてよくなる。 sliceは新しいlistを作成するため、元のlistに影響しない。

1
2
3
4
5
6
7
8
list = [1, 2, 3, 4, 5]
print(list[1:4])
print(list[0:1])
print(list[1:])
print(list[-1:])
print(list[-2:])
print(list[:-2])
print('1234567890'[:8])
1
2
3
4
5
6
7
[2, 3, 4]
[1]
[2, 3, 4, 5]
[5]
[4, 5]
[1, 2, 3]
12345678

enumrate

counterの値をプラスした値をiterateできるジェネレータを返す。

1
2
3
list = ['zero', 'one', 'two' , 'three', 'four']
for key, val in enumerate(list):
    print(key , ':' , val)
1
2
3
4
5
0 : zero
1 : one
2 : two
3 : three
4 : four

yield

yieldを用いて、Listの結果自身ではなく、Listを生成するGeneratorを返却するようにすれば、 例えば巨大なListを扱う必要がある場合もメモリを逼迫させることなく処理を行うことができる。

1
2
3
4
5
6
7
8
def list_gen():
    yield 0

    for i in range(1, 10):
	yield i

for i in list_gen():
    print(i)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
0
1
2
3
4
5
6
7
8
9

empty 空リスト判定

len(lst) == 0

インデックス要素の削除

1
2
# 値を返す
list.pop(index)

https://www.pythonweb.jp/tutorial/list/index8.html

stack

listでstackを実現するにはappendとpopを使う。

1
2
3
4
5

lis  = [3, 4, 5]
lis.append(6)
lis.pop()
-> 6

https://docs.python.org/3.1/tutorial/datastructures.html

listをある値で初期化する

1
2
lis = [0] * 4
print(lis)

zip リストの要素を同時に取得して処理したい場合

1
2
3
4
5
i = [1, 2, 3]
k = [4, 5, 6]
j = zip(i, k)
for p, q in j:
    print(p, q)
1
2
3
1 4
2 5
3 6

dictionary

1
2
3
4
5
6
val = {'hoge': [9], 'fuga': [0], 'hige': []}
print(val.get('hige'))

# keyが存在しないとNoneが返る。デフォルト値を第二引数に渡せる
print(val.get('hage'))
print(val.get('hage', []))

string

文字列の変換 https://stackoverflow.com/questions/8270092/python-remove-all-whitesplace-in-a-string

文字列を掛け算すると、与えられた文字列が繰り返される。

1
2
print('4' * 3)
print(int('4') * 3)
1
2
444
12

sort

list.sort() と sorted(list)の違い

sorted()は新しいlistを、list.sort()はそのlist自体を変更する。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
numbers = [8,3,1,2,5,4,7,6]
# 昇順
print(sorted(numbers))
# 降順
print(sorted(numbers,reverse=True))

def iseven(x):
    if (x % 2) == 0:
	return (0, x)
    return (1, x)

# コンパレータを渡す
print(sorted(numbers, key=iseven))
1
2
3
[1, 2, 3, 4, 5, 6, 7, 8]
[8, 7, 6, 5, 4, 3, 2, 1]
[2, 4, 6, 8, 1, 3, 5, 7]

unitttest

https://qiita.com/hoto17296/items/fa0166728177e676cd36

tests ディレクトリ内のすべてのテストケースを実行する

1
$ python -m unittest discover tests

ひとつのテストケースだけを実行する

$ python -m unittest tests.test_foo

unittestでpdbを起動

コード中に下記を記述

1
import pdb; pdb.set_trace()  # デバッグコード

https://qiita.com/TakesxiSximada/items/45b6d71a44f2706798ed

mysql util mentenance

sudo pip install mysql-connector==2.1.4 https://stackoverflow.com/questions/43029672/unable-to-find-protobuf-include-directory

python programing

関数

引数は全て参照渡し デフォルト値には同じオブジェクトがわたさる

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> def hoge(foo, bar=[]):
...   bar.append(foo)
...   return bar

>>> print(hoge('a'))
['a']
>>> print(hoge('a'))
['a', 'a']
>>> print(hoge('a'))
['a', 'a', 'a']

nolocal: 1つ外側のスコープに属する変数への代入が可能になる

可変長引数

アスタ(*)で表現する

1
2
3
4
5
def hoge(foo, bar, *arg):
    print(foo,bar,arg)

>>> hoge('a', 'b', 'c', 'd')
a b ('c', 'd')

クラス

コンストラクタは__init__

numpy

1
2
import numpy as np
return np.arange(0, 6, 0.1)
00.10.20.30.40.50.60.70.80.911.11.21.31.41.51.61.71.81.922.12.22.32.42.52.62.72.82.933.13.23.33.43.53.63.73.83.944.14.24.34.44.54.64.74.84.955.15.25.35.45.55.65.75.85.9

0から6 まで0.1ずつ増やした値を出力

ndim(A) 配列の次元数をだす

1
2
3
4
5
6
7
import numpy as np

A = np.array([1, 2, 3, 4])
B = np.array([[1, 2],[ 3, 4]])

print(np.ndim(A))
print(np.ndim(B))
1
2
1
2

dot(X, Y) ドット積

1
2
3
4
5
import numpy as np

A = np.array([[1,2], [3,4]])
B = np.array([[5,6],[7,8]])
return np.dot(A,B)
1922
4350

ctypes

1
2
3
4
5
6
7
8

import ctypes

PyArray = ctypes.py_object * 2
x = PyArray()

x[0] = 0
x[1] = 1

array

配列の宣言

1
2
3
4
5
6
7
8
9
import sys

# 0で初期化した length 3の配列
A = []
print(sys.getsizeof(A))
A = [0] * int(3)
print(sys.getsizeof(A))
A = ['hoge'] * int(7)
print(sys.getsizeof(A))
1
2
3
72
96
128

format

1
2
print('hoge %s hige' % ('fuga'))
print('hoge %s %s' % ('fuga', 'hige'))
1
2
hoge fuga hige
hoge fuga hige

fプリフィックスによるテンプレート

1
2
3
4
val1 = 'fuga'
val2 = 'hige'
print(f'hoge {val1} hige')
print(f'hoge {val1} {val2}')
1
2
hoge fuga hige
hoge fuga hige

Share