{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python入門 〜基本文法編〜" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## TL;DR\n", "[http://diveintopython3-ja.rdy.jp](http://diveintopython3-ja.rdy.jp) を読めばすべてわかる. \n", "環境構築は[https://github.com/johshisha/python_hands_on](https://github.com/johshisha/python_hands_on) を参照するか, ぐぐってくだしあ." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## はじめ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pythonはインタプリタ(一行ずつ実行される)言語だよ" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Pythonic world!\n" ] } ], "source": [ "print(\"Hello, Pythonic world!\")\n", "# これはコメント" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 本編" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 変数\n", "変数には「型」がない, 値に「型」がある \n", "変数自体はただの入れ物で,中身に種類があるイメージ \n", "ちなみにPythonに定数はない" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2017\n", "\n" ] } ], "source": [ "x = 2017\n", "print(x)\n", "print(type(x))" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.141592653\n", "\n" ] } ], "source": [ "pi = 3.141592653\n", "print(pi)\n", "print(type(pi))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "\n" ] } ], "source": [ "flag = True\n", "print(flag)\n", "print(type(flag))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "こんにちは 世界\n", " \n" ] } ], "source": [ "s = \"こんにちは\"\n", "t = \"世界\"\n", "print(s, t)\n", "print(type(s), type(t))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "祇園精舎の鐘の声\n", "諸行無常の響きあり\n" ] } ], "source": [ "sentence = \"\"\"祇園精舎の鐘の声\n", "諸行無常の響きあり\"\"\"\n", "print(sentence)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4649\n", "\n", "4649\n", "\n" ] } ], "source": [ "yoroshiku = \"4649\"\n", "print(yoroshiku)\n", "print(type(yoroshiku))\n", "yoroshiku = int(yoroshiku)\n", "print(yoroshiku)\n", "print(type(yoroshiku))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 演算" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 + 1" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 * 2" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.5" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 / 2" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7 % 3" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 ** 2" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "100 == 100 or 100 != 100" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "100 == 100 and 100 != 100" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "not 100 != 100" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### if elif else\n", "コロンを忘れずに" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "現在\n" ] } ], "source": [ "year = 2017\n", "if year > 2017:\n", " print(\"未来\")\n", "elif year < 2017:\n", " print(\"過去\")\n", "else:\n", " print(\"現在\")" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20世紀だね\n" ] } ], "source": [ "year = 2000\n", "if 1991 <= year < 2001:\n", " print(\"20世紀だね\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### (Trueの時) if (条件式) else (Falseの時)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "odd\n" ] } ], "source": [ "val = 39\n", "result = \"even\" if val % 2 == 0 else \"odd\"\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### == か is か\n", "is は同じオブジェクトかどうかをチェックする" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "str_a = \"林檎スター\"\n", "str_b = \"林檎スター\"" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4514509992\n", "4514512384\n" ] } ], "source": [ "print(id(str_a))\n", "print(id(str_b))" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "str_a == str_b\n" ] } ], "source": [ "if str_a == str_b:\n", " print(\"str_a == str_b\")\n", "else:\n", " print(\"str_a != str_b\")" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "str_a is not str_b\n" ] } ], "source": [ "if str_a is str_b:\n", " print(\"str_a is str_b\")\n", "else:\n", " print(\"str_a is not str_b\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### list\n", "Pythonには配列はなく,もっと便利なリストを使う" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "empty = []\n", "print(type(empty))" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'banana', 'peach']\n" ] } ], "source": [ "fruits = [\"apple\", \"banana\", \"peach\"]\n", "print(fruits)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n" ] } ], "source": [ "print(fruits[0])" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'banana', 'peach', 'lemmon']\n", "4\n" ] } ], "source": [ "fruits.append(\"lemmon\")\n", "print(fruits)\n", "print(len(fruits))" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple + banana + peach + lemmon\n" ] } ], "source": [ "print(\" + \".join(fruits))" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['apple', 'banana', 'peach', 'lemmon']" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"apple,banana,peach,lemmon\".split(\",\")" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "レモン入りです\n", "オレンジはないです\n" ] } ], "source": [ "if \"lemmon\" in fruits:\n", " print(\"レモン入りです\")\n", "if \"orange\" not in fruits:\n", " print(\"オレンジはないです\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "リストは何でも入れられる" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['もじ', 50, 3.14, ['a']]\n" ] } ], "source": [ "print(['もじ', 50, 3.14, [\"a\"]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### マイナスの添字とスライス\n", "マイナスの添字は後ろから,スライスは範囲指定" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "numbers = [0, 1, 2, 3, 4, 5]\n", "numbers += [6, 7, 8, 9]\n", "print (numbers)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9 9\n", "7 7\n" ] } ], "source": [ "print(numbers[-1], numbers[len(numbers) - 1])\n", "print(numbers[-3], numbers[7])" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5]\n", "[3, 4, 5, 6, 7, 8, 9]\n", "[5, 6]\n" ] } ], "source": [ "print(numbers[:6])\n", "print(numbers[3:])\n", "print(numbers[5: -3])" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 4, 6, 8]\n", "[0, 3, 6, 9]\n", "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n" ] } ], "source": [ "print(numbers[::2])\n", "print(numbers[::3])\n", "print(numbers[::-1], list(reversed(numbers)))" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0001\n", "0020\n", "0300\n", "0020\n" ] } ], "source": [ "print((\"000\" + \"1\")[-4:])\n", "print((\"000\" + \"20\")[-4:])\n", "print((\"000\" + \"300\")[-4:])\n", "print(\"20\".zfill(4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### リストのコピー\n", "immutableなオブジェクト(数値・文字列・タプルなど)は素直にコピーできる \n", "mutableなオブジェクト(リスト・オブジェクトなど)はポインタっぽくなってるので, \n", "「=」でのコピーは意図しない結果になる. \n", "Pythonでの「=」は代入ではなく束縛(bind)." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n", "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n" ] } ], "source": [ "zero_vec = [0] * 10\n", "print(zero_vec)\n", "copy_vec = zero_vec\n", "print(copy_vec)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]\n", "[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]\n", "4514647496\n", "4514647496\n" ] } ], "source": [ "copy_vec[1] = 1\n", "print(copy_vec)\n", "print(zero_vec)\n", "print(id(copy_vec))\n", "print(id(zero_vec))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "スライスを使うとコピーが発生する \n", "(もしくはcopy.deepcopyを利用)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n", "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n" ] } ], "source": [ "zero_vec = [0] * 10\n", "print(zero_vec)\n", "copy_vec = zero_vec[:]\n", "print(copy_vec)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]\n", "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n", "4514691720\n", "4514645064\n" ] } ], "source": [ "copy_vec[1] = 1\n", "print(copy_vec)\n", "print(zero_vec)\n", "print(id(copy_vec))\n", "print(id(zero_vec))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### tuple\n", "リストの変更できないver. \n", "変更する予定のないものはタプルにしておくと安心" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "empty = ()\n", "print(type(empty))" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('apple', 'banana', 'peach')\n", "apple\n", "('banana', 'apple')\n" ] } ], "source": [ "fruits = (\"apple\", \"banana\", \"peach\")\n", "print(fruits)\n", "print(fruits[0])\n", "print(fruits[1::-1])" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'tuple' object has no attribute 'append'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfruits\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"lemmon\"\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# 失敗する\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'append'" ] } ], "source": [ "fruits.append(\"lemmon\") # 失敗する" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### タプルパック,シーケンスアンパック\n", "タプルパック - カンマ区切りで代入するとタプルになる \n", "シーケンスアンパック - 要素数があえば分割してくれる" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, 3)\n" ] } ], "source": [ "pack = 1, 2, 3\n", "print(pack)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "あ\n", "い\n", "う\n" ] } ], "source": [ "a, b, c = \"あいう\"\n", "print(a)\n", "print(b)\n", "print(c)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3 5\n", "5 3\n" ] } ], "source": [ "a = \"3\"\n", "b = \"5\"\n", "print(a, b)\n", "a, b = b, a\n", "print(a, b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ループ\n", "Pythonのfor文はイテレータ(先頭から一個ずつ取り出すやつ)を使う" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n" ] } ], "source": [ "for i in [0, 1, 2, 3]:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "range(0, 4)\n", "[0, 1, 2, 3]\n", "[1, 2, 3, 4]\n" ] } ], "source": [ "print(range(4))\n", "print(list(range(4)))\n", "print(list(range(1, 5)))" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 apple\n", "1 banana\n", "2 peach\n" ] } ], "source": [ "for i in range(len(fruits)):\n", " print(i, fruits[i])" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "banana\n", "peach\n" ] } ], "source": [ "for fruit in fruits:\n", " print(fruit)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "enumerateを使えば「今何問目?」という問いにも答えられる" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 apple\n", "1 banana\n", "2 peach\n" ] } ], "source": [ "for i, fruit in enumerate(fruits):\n", " print(i, fruit)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 組み合わせを書くときのテク \n", "itertoolsには組み合わせ,順列などを簡単に作ってくれる関数がある \n", "※下2つは同じ結果になる" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple and banana\n", "apple and peach\n", "banana and peach\n" ] } ], "source": [ "for i, fruit1 in enumerate(fruits):\n", " for j, fruit2 in enumerate(fruits):\n", " if i < j:\n", " print(fruit1 + \" and \" + fruit2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "importはモジュール(Pythonのライブラリ)を読み込む" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple and banana\n", "apple and peach\n", "banana and peach\n" ] } ], "source": [ "import itertools\n", "\n", "for fruit1, fruit2 in itertools.combinations(fruits, 2):\n", " print(fruit1 + \" and \" + fruit2) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### for else\n", "breakされずに最後までfor文が終わった時,elseを行う" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "異常なし\n" ] } ], "source": [ "people = [\"a\", \"b\", \"c\", \"d\"]\n", "lupin = \"x\"\n", "for person in people:\n", " if person == lupin:\n", " print(\"そいつがルパンだ\")\n", " break\n", "else:\n", " print(\"異常なし\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### while \n", "もあるよ\n", "- 関数じゃないとスコープをつくらない\n", "- やらない処理はpassを書く\n", "- ++とかのインクリメンタル演算子はない" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(6.0, 7.0)\n" ] } ], "source": [ "i = 1\n", "while True:\n", " if i % 56 == 0 and i % 48 == 0:\n", " j = i/56, i/48\n", " break\n", " else:\n", " pass\n", " i += 1\n", "print(j)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### dictionary\n", "一対一対応で結び付けたいときのデータ構造 \n", "辞書,ハッシュ,連想配列などプログラミング言語によって呼び名は様々" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "※ 順番は保持されない" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "empty = {}\n", "print(type(empty))" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'吉田': 30, '鈴木': 28, '田中': 25}\n", "\n" ] } ], "source": [ "name2age = {\n", " \"吉田\": 30,\n", " \"鈴木\": 28,\n", " \"田中\": 25\n", "}\n", "print(name2age)\n", "print(type(name2age))" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "28\n" ] } ], "source": [ "print(name2age[\"鈴木\"])" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'吉田': 30, '鈴木': 28, '田中': 25, '新島 襄': 174}\n" ] } ], "source": [ "name2age[\"新島 襄\"]=2017-1843\n", "print(name2age)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "佐藤さんの年齢は不明\n" ] } ], "source": [ "person = \"佐藤\"\n", "if person not in name2age:\n", " print(person+\"さんの年齢は不明\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ループでデータを一通り見たい時" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "吉田\n", "鈴木\n", "田中\n", "新島 襄\n" ] } ], "source": [ "for name in name2age:\n", " print(name)" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "30\n", "28\n", "25\n", "174\n" ] } ], "source": [ "for age in name2age.values():\n", " print(age)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "吉田さんは30歳です\n", "鈴木さんは28歳です\n", "田中さんは25歳です\n", "新島 襄さんは174歳です\n" ] } ], "source": [ "for name, age in name2age.items():\n", " print(\"{0}さんは{1}歳です\".format(name, age))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### set\n", "集合型.重複を許さないデータ構造. \n", "集合演算が便利." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "※ dictionaryと同じく順不同" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "empty = set()\n", "print(type(empty))" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['塩', '胡椒', '塩', '砂糖', '塩']\n", "\n", "{'塩', '砂糖', '胡椒'}\n", "\n" ] } ], "source": [ "seasoning = [\"塩\", \"胡椒\", \"塩\", \"砂糖\", \"塩\"]\n", "print(seasoning)\n", "print(type(seasoning))\n", "\n", "seasoning = set(seasoning)\n", "print(seasoning)\n", "print(type(seasoning))" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "set1 = {\"A\", \"B\", \"C\"}\n", "set2 = {\"B\", \"C\", \"D\"}" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A', 'B', 'C', 'D'}" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1 | set2" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'B', 'C'}" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1 & set2" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A', 'D'}" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1 ^ set2" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A'}" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1 - set2" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'D'}" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set2 - set1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### defaultdict\n", "空っぽの要素にアクセスしてもエラーにならないdictionary." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### それぞれの要素のカウントをしたい時(BoWを作る時など) \n", "dictionaryでカウントすると場合分けが必要 \n", "(カウントだけならcollections.Counterの方が便利だけど)" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "sentence = \"Peter Piper picked a peck of pickled peppers.\"\n", "print(sentence.count(\"e\"))" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{' ': 7,\n", " '.': 1,\n", " 'P': 2,\n", " 'a': 1,\n", " 'c': 3,\n", " 'd': 2,\n", " 'e': 8,\n", " 'f': 1,\n", " 'i': 3,\n", " 'k': 3,\n", " 'l': 1,\n", " 'o': 1,\n", " 'p': 7,\n", " 'r': 3,\n", " 's': 1,\n", " 't': 1}" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alphabet_counter = {}\n", "\n", "for alphabet in sentence:\n", " if alphabet in alphabet_counter:\n", " alphabet_counter[alphabet] += 1\n", " else:\n", " alphabet_counter[alphabet] = 1\n", "alphabet_counter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "collections.defaultdictを使うと便利" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "defaultdict(int,\n", " {' ': 7,\n", " '.': 1,\n", " 'P': 2,\n", " 'a': 1,\n", " 'c': 3,\n", " 'd': 2,\n", " 'e': 8,\n", " 'f': 1,\n", " 'i': 3,\n", " 'k': 3,\n", " 'l': 1,\n", " 'o': 1,\n", " 'p': 7,\n", " 'r': 3,\n", " 's': 1,\n", " 't': 1})" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from collections import defaultdict\n", "alphabet_counter = defaultdict(int)\n", "\n", "for alphabet in sentence:\n", " alphabet_counter[alphabet] += 1\n", "alphabet_counter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ちなみにsortedを使うとリストでも辞書でもなんでもソートできる \n", "(名前付き引数をつかっています)" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('e', 8),\n", " (' ', 7),\n", " ('p', 7),\n", " ('r', 3),\n", " ('i', 3),\n", " ('c', 3),\n", " ('k', 3),\n", " ('P', 2),\n", " ('d', 2),\n", " ('t', 1),\n", " ('a', 1),\n", " ('o', 1),\n", " ('f', 1),\n", " ('l', 1),\n", " ('s', 1),\n", " ('.', 1)]" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(alphabet_counter.items(),key = lambda x: x[1], reverse=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 二重defaultdict\n", "defaultdictを二重にするときは注意 \n", "defaultdictの引数はcallableでなくてはならないので,ラムダ式を使う" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "first argument must be callable or None", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdouble_dict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdefaultdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdefaultdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mint\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: first argument must be callable or None" ] } ], "source": [ "double_dict = defaultdict(defaultdict(int))" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "defaultdict(>,\n", " {'カツオ': defaultdict(int, {'花沢': 'フォローしていない'}),\n", " '花沢': defaultdict(int, {'カツオ': 'フォロー'})})" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "double_dict = defaultdict(lambda : defaultdict(int))\n", "double_dict[\"花沢\"][\"カツオ\"] = \"フォロー\"\n", "double_dict[\"カツオ\"][\"花沢\"] = \"フォローしていない\"\n", "double_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### None\n", "Pythonでのnull(空っぽ)はNoneで表す" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, None, 4]\n", "None\n" ] } ], "source": [ "values = [3, None, 4]\n", "print(values)\n", "print(values[1])" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "3\n", "4\n", "4\n" ] } ], "source": [ "for val in values:\n", " if val is not None:\n", " print(val)\n", " if val:\n", " print(val)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### pickle\n", "オブジェクトのSerialize(直列化).変数をそのまま保存する. \n", "テキストファイルに毎回書き出してとかはめんどくさいので便利." ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'ごりら': 1, 'ぱせり': 3, 'らっぱ': 2, 'りんご': 0}" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "siritori = {\n", " \"りんご\": 0,\n", " \"ごりら\": 1,\n", " \"らっぱ\": 2,\n", " \"ぱせり\": 3\n", "}\n", "siritori" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [], "source": [ "import pickle\n", "file = open(\"siritori.pkl\", \"wb\")\n", "pickle.dump(siritori, file, pickle.HIGHEST_PROTOCOL)\n", "file.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "!を行頭に書くとシェルのコマンドを実行できる" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total 1648\r\n", "drwxr-xr-x 13 arakimm staff 442 9 28 13:02 \u001b[1m\u001b[36m.\u001b[m\u001b[m\r\n", "drwxr-xr-x 10 arakimm staff 340 9 26 13:21 \u001b[1m\u001b[36m..\u001b[m\u001b[m\r\n", "-rw-r--r--@ 1 arakimm staff 10244 9 25 16:09 .DS_Store\r\n", "drwxr-xr-x 4 arakimm staff 136 9 25 14:52 \u001b[1m\u001b[36m.ipynb_checkpoints\u001b[m\u001b[m\r\n", "-rw-r--r-- 1 arakimm staff 57910 9 28 13:02 Python01.ipynb\r\n", "-rw-r--r-- 1 arakimm staff 738600 9 25 15:16 Python02.ipynb\r\n", "drwxr-xr-x 2 arakimm staff 68 9 25 14:25 \u001b[1m\u001b[36m_static\u001b[m\u001b[m\r\n", "drwxr-xr-x 2 arakimm staff 68 9 25 14:25 \u001b[1m\u001b[36m_templates\u001b[m\u001b[m\r\n", "-rw-r--r-- 1 arakimm staff 5948 9 25 14:25 conf.py\r\n", "-rw-r--r-- 1 arakimm staff 386 9 25 14:45 index.rst\r\n", "-rw-r--r-- 1 arakimm staff 2419 9 25 15:16 predict_result.csv\r\n", "-rw-r--r-- 1 arakimm staff 72 9 28 13:03 siritori.pkl\r\n", "-rw-r--r-- 1 arakimm staff 5027 9 25 15:16 svc.pkl.cmp\r\n" ] } ], "source": [ "!ls -la" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'ごりら': 1, 'ぱせり': 3, 'らっぱ': 2, 'りんご': 0}" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "file = open(\"siritori.pkl\", \"rb\")\n", "siritori2 = pickle.load(file)\n", "file.close()\n", "siritori2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ファイルをcloseし忘れると良くないのでwith文を使おう \n", "withのスコープを抜けると自動でclose \n", "(ガベッジコレクションに処理されると自動でcloseされるが)" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [], "source": [ "with open(\"siritori.pkl\", \"wb\") as f:\n", " pickle.dump(siritori, f, pickle.HIGHEST_PROTOCOL)" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'ごりら': 1, 'ぱせり': 3, 'らっぱ': 2, 'りんご': 0}" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "with open(\"siritori.pkl\", \"rb\") as f:\n", " siritori2 = pickle.load(f)\n", "siritori2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Q.** pickle.dumpが失敗する \n", "**A.** Serializeできないオブジェクト(generatorなど)が含まれている \n", " →dillを使ってみる \n", "**A.** オブジェクトが大き過ぎる \n", " →joblib.dumpを使ってみる" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 関数\n", "Pythonの関数を簡単に \n", "Pythonは変数の型を実行時にチェックするので注意" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [], "source": [ "def average(arg_a, arg_b):\n", " return (arg_a + arg_b)/ 2" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.5" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "average(3, 4)" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for /: 'str' and 'int'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0maverage\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"a\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"b\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36maverage\u001b[0;34m(arg_a, arg_b)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0maverage\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0marg_a\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0marg_b\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0marg_a\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0marg_b\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m/\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'int'" ] } ], "source": [ "average(\"a\", \"b\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### デフォルト引数\n", "引数がなかった時のデフォルト値を指定できる" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [], "source": [ "def pow(x, y=2):\n", " return x ** y" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "27\n" ] } ], "source": [ "print(pow(3))\n", "print(pow(3, 3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### キーワード引数\n", "仮引数名を使って実引数を与えることができる" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [], "source": [ "def info(name, address, age):\n", " print(\"{1}にお住まいの{0}さん({2})\".format(name, address, age))" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "佐賀県にお住まいのはなわさん(41)\n" ] } ], "source": [ "info(\"はなわ\", \"佐賀県\", 41)" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "佐賀県にお住まいのはなわさん(41)\n" ] } ], "source": [ "info(address=\"佐賀県\", age=41, name=\"はなわ\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### その他テク" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 実行時間を確かめる\n", "プログラムが遅すぎると実験可能回数が減ってしまう \n", "ボトルネックを確かめる方法として実行時間を測るという方法がある \n", "jupyterではマジックコマンドを使って簡単に実行時間を測ることができる" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.1 ms ± 109 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] } ], "source": [ "%%timeit\n", "array = []\n", "for x in range(10000):\n", " array.append(x)" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "391 µs ± 46.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] } ], "source": [ "%%timeit\n", "array = [x for x in range(10000)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### メモリ使用量を確かめる \n", "時間計算量と空間計算量はたいていトレードオフ \n", "メモリを食いすぎている変数がないか確かめることも大事 \n", "特にjupyterでは使用できるメモリがデフォルトでは限られている模様 \n", "(jupyter generate-configで検索と増やす方法が出るかも)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "正しいメモリ使用量を知るにはパッケージ等を導入する必要があるが, \n", "jupyterのマジックコマンドで簡易的に変数の状態を知ることはできる" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [], "source": [ "array = [x for x in range(10000)]" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Variable Type Data/Info\n", "----------------------------------------------\n", "a str 5\n", "age int 174\n", "alphabet str .\n", "alphabet_counter defaultdict defaultdict(<...> 'l': 1, 's': 1, '.': 1})\n", "array list n=10000\n", "average function \n", "b str 3\n", "c str う\n", "copy_vec list n=10\n", "defaultdict type \n", "double_dict defaultdict defaultdict(>, {'花沢': 'フォローしていない'})})\n", "empty set set()\n", "f BufferedReader <_io.BufferedReader name='siritori.pkl'>\n", "file BufferedReader <_io.BufferedReader name='siritori.pkl'>\n", "flag bool True\n", "fruit str peach\n", "fruit1 str banana\n", "fruit2 str peach\n", "fruits tuple n=3\n", "i int 336\n", "info function \n", "itertools module \n", "j tuple n=2\n", "lupin str x\n", "name str 新島 襄\n", "name2age dict n=4\n", "numbers list n=10\n", "pack tuple n=3\n", "people list n=4\n", "person str 佐藤\n", "pi float 3.141592653\n", "pickle module lib/python3.6/pickle.py'>\n", "pow function \n", "result str odd\n", "s str こんにちは\n", "seasoning set {'塩', '砂糖', '胡椒'}\n", "sentence str Peter Piper picked a peck of pickled peppers.\n", "set1 set {'B', 'C', 'A'}\n", "set2 set {'B', 'C', 'D'}\n", "siritori dict n=4\n", "siritori2 dict n=4\n", "str_a str 林檎スター\n", "str_b str 林檎スター\n", "t str 世界\n", "val int 4\n", "values list n=3\n", "x int 2017\n", "year int 2000\n", "yoroshiku int 4649\n", "zero_vec list n=10\n" ] } ], "source": [ "%whos" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [], "source": [ "del array" ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Variable Type Data/Info\n", "----------------------------------------------\n", "a str 5\n", "age int 174\n", "alphabet str .\n", "alphabet_counter defaultdict defaultdict(<...> 'l': 1, 's': 1, '.': 1})\n", "average function \n", "b str 3\n", "c str う\n", "copy_vec list n=10\n", "defaultdict type \n", "double_dict defaultdict defaultdict(>, {'花沢': 'フォローしていない'})})\n", "empty set set()\n", "f BufferedReader <_io.BufferedReader name='siritori.pkl'>\n", "file BufferedReader <_io.BufferedReader name='siritori.pkl'>\n", "flag bool True\n", "fruit str peach\n", "fruit1 str banana\n", "fruit2 str peach\n", "fruits tuple n=3\n", "i int 336\n", "info function \n", "itertools module \n", "j tuple n=2\n", "lupin str x\n", "name str 新島 襄\n", "name2age dict n=4\n", "numbers list n=10\n", "pack tuple n=3\n", "people list n=4\n", "person str 佐藤\n", "pi float 3.141592653\n", "pickle module lib/python3.6/pickle.py'>\n", "pow function \n", "result str odd\n", "s str こんにちは\n", "seasoning set {'塩', '砂糖', '胡椒'}\n", "sentence str Peter Piper picked a peck of pickled peppers.\n", "set1 set {'B', 'C', 'A'}\n", "set2 set {'B', 'C', 'D'}\n", "siritori dict n=4\n", "siritori2 dict n=4\n", "str_a str 林檎スター\n", "str_b str 林檎スター\n", "t str 世界\n", "val int 4\n", "values list n=3\n", "x int 2017\n", "year int 2000\n", "yoroshiku int 4649\n", "zero_vec list n=10\n" ] } ], "source": [ "%whos" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "その他マジックコマンドは%quickrefで確認できる" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 実行を一時停止する" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Pythonの実行中にインタラクティブシェルを起動する](https://qiita.com/taise/items/063829ac89bf1def36d0)\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## おわりに" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ここに書いた文法はごく一部 \n", "http://diveintopython3-ja.rdy.jp を読んだり, \n", "公式ドキュメントhttps://docs.python.jp/3/index.html を読むとより詳しく理解できるだろう \n", " \n", "基本的には「やりたいこと python」で検索すればなんとかなるでしょう \n", "**車輪の再発明**にならないよう,既存のモジュールもよく調べよう " ] }, { "cell_type": "code", "execution_count": 99, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The Zen of Python, by Tim Peters\n", "\n", "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n", "Complex is better than complicated.\n", "Flat is better than nested.\n", "Sparse is better than dense.\n", "Readability counts.\n", "Special cases aren't special enough to break the rules.\n", "Although practicality beats purity.\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "In the face of ambiguity, refuse the temptation to guess.\n", "There should be one-- and preferably only one --obvious way to do it.\n", "Although that way may not be obvious at first unless you're Dutch.\n", "Now is better than never.\n", "Although never is often better than *right* now.\n", "If the implementation is hard to explain, it's a bad idea.\n", "If the implementation is easy to explain, it may be a good idea.\n", "Namespaces are one honking great idea -- let's do more of those!\n" ] } ], "source": [ "import this" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ">醜いより美しいほうがいい。 \n", ">暗示するより明示するほうがいい。 \n", ">複雑であるよりは平易であるほうがいい。 \n", ">それでも、込み入っているよりは複雑であるほうがまし。 \n", ">ネストは浅いほうがいい。 \n", ">密集しているよりは隙間があるほうがいい。 \n", ">読みやすいことは善である。 \n", ">特殊であることはルールを破る理由にならない。 \n", ">しかし、実用性を求めると自然さが失われることがある。 \n", ">エラーは隠すな、無視するな。 \n", ">ただし、わざと隠されているのなら見逃せ。 \n", ">曖昧なものに出逢ったら、その意味を適当に推測してはいけない。 \n", ">たったひとつの冴えたやりかたがあるはずだ。 \n", ">そのやり方は一目見ただけではわかりにくいかもしれない。オランダ人にだけわかりやすいなんてこともあるかもしれない。 \n", ">ずっとやらないでいるよりは、今やれ。 \n", ">でも、今\"すぐ\"にやるよりはやらないほうがマシなことが多い。 \n", ">コードの内容を説明するのが難しいのなら、それは悪い実装である。 \n", ">コードの内容を容易に説明できるのなら、おそらくそれはよい実装である。 \n", ">名前空間は優れたアイデアであるため、積極的に利用すべきである。 " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.2" } }, "nbformat": 4, "nbformat_minor": 2 }