Python enumerate()の使い方

enumerate()関数を利用することで、for文内のループ処理にインデックス番号を付与できる

ary = ['ドル', 'ユーロ', 'ポンド', 'リラ']
for i, d in enumerate(ary):
    print('index:' + str(i) + ' 通貨:' + d)

$ python3 test.py
index:0 通貨:ドル
index:1 通貨:ユーロ
index:2 通貨:ポンド
index:3 通貨:リラ

Python bytearray()

bytearray() method returns a bytearray object which is an array of given bytes.

prime = [2, 3, 5, 7]

print(bytearray(prime))

$ python3 test.py
bytearray(b’\x02\x03\x05\x07′)

0 <= x < 256 の整数

Python 関数を数字(数字コード)で実行する方法

def OP_NOP():
    print("This is OP_NOP, 76")

def OP_IF():
    print("This is OP_IF, 99")

def OP_NOTIF():
    print("This is OP_NOTIF, 100")

OP_CODE = {
    76: OP_NOP,
    99: OP_IF,
    100: OP_NOTIF
}

func = OP_CODE[76]
func()

$ python3 test.py
This is OP_NOP, 76

bitcoinのOPcode一覧はこちら
https://en.bitcoin.it/wiki/Script

めちゃくちゃお洒落な書き方だな~

Python if not condition

a = True

if not a:
    print('a is false')

in String

a = ''

if not a:
    print('a is empty')
def mul(num):
    if type(num) == int:
        print(num * 2)
        return True
    else:
        return False

n = 'a'
if not mul(n):
    print('please input number')

if notは基本的にTrue or Falseを判定している

PythonのLogging

シンプルなログ出力はお馴染みのprint文

print("I am the simplest log.")

ファイル出力、メール送信、HTTP通信など動作ログをよりフレキシブルに出力したい場合にはloggingモジュールを使用してログを出力する。

### ログレベル
DEBUG, INFO, WARNING, ERROR, CRITICAL

出力

import logging 

logging.info("info log")
logging.warning("warning log")

$ python3 test.py
WARNING:root:warning log

info はコマンドラインに出力されない
loggerオブジェクトを取得してログを出力する

import logging 

logger = logging.getLogger("sample")
logger.info("info log")
logger.warning("warning log")

$ python3 test.py
warning log

import logging 

logger = logging.getLogger("sample")
logger.setLevel(logging.DEBUG)
logger.info("info log")
logger.warning("warning log")

### ハンドラ
StreamHandler, FileHandler, SMTPHandler, HTTPHandlerがある

import logging 

logger = logging.getLogger("sample")
logger.setLevel(logging.DEBUG)


st_handler = logging.StreamHandler()

logger.addHandler(st_handler)
logger.info("info log")
logger.warning("warning log")

handlerで指定することでログ出力をカスタマイズできる。

Python stackのpopとpush

class MyStack:
    def __init__(self):
        self.stack = []
    
    def push(self, item):
        self.stack.append(item)

    def pop(self):
        pass

mystack = MyStack()
mystack.push(0)
mystack.push(1)
mystack.push(2)
print(mystack.stack)

$ python3 test.py
[0, 1, 2]

pop

    def pop(self):
        result = self.stack[-1]
        del self.stack[-1]
        return result

print(mystack.pop())
print(mystack.pop())

取り出して削除なので、[-1]の後にdelを実行している。
上記と同じことをpop()と書くことができる。

    def pop(self):
        return self.stack.pop()

stackが0の場合があるので、例外処理も書かなければならない。

    def pop(self):
        if len(self.stack) == 0:
            return None
        return self.stack.pop()

PythonのBytesIO

BytesIOはメモリ上でバイナリデータを扱うための機能
同様な機能としてStringIO, cStringIOがある

import io
import urllib.request
from PIL import Image

url = "https://www.python.org/static/img/python-logo@2x.png"
img_in = urllib.request.urlopen(url).read()
img_bin = io.BytesIO(img_in)
img = Image.open(img_bin)
img.save("logo.png","PNG")
print(img_bin.getvalue())

Pythonのstream

I/O : 入出力input/outputのこと
stream: データが流れる通り道

Pythonおいてストリームを作り簡単な方法はファイルをopenすること
読み取りのストリームにはread(), tell(), seekなどのインターフェイスが用意されている
tellは読み取り位置取得、seekは読み取り位置変更

text_file.txt
1234567890abcdefg

f = open("text_file.txt", "r")
print("tell 1 ->", f.tell())

first4 = f.read(4)
print("first4 ->", first4)
print("tell2 ->", f.tell())
f.seek(10)
last = f.read()
print("last ->", last)
f.close()

$ python3 test.py
tell 1 -> 0
first4 -> 1234
tell2 -> 4
last -> abcdefg