3種類の平均について
平均について復習。
参考URL
wikipedia:平均
相加平均
最も基本的な平均は相加平均(そうかへいきん)である。算術平均(さんじゅつへいきん 英語: arithmetic mean)とも呼ぶ。
単に平均といった場合はこれを意味する。
例:
人 体重
A 60kg
B 75kg
C 80kg
このとき3人の体重の平均は、
(60 + 75 + 80) / 3 = 71.666...
となり、72kgとである。
相乗平均
相乗平均は数学における平均の一種で、数値群の代表値である。それぞれの数値を足すのではなくかけ、
その積の冪根(数値がn個ならn乗根)をとることで得られる。
例:
78年の経済成長率20%、79年の経済成長率80%の場合、
この2年間の平均成長率は、
sqrt(1.2 * 1.8) = 1.469...
となり、47%とである。
調和平均
調和平均は、逆数の相加平均の逆数である。あるいは、逆数の相加平均は調和平均の逆数である。
例:
往は時速60km、復は時速90kmの場合の往復の平均速度は、
2 / ( (1/60) + (1/90) ) = 72
となり、時速72kmである。
python復習まとめ5
リスト内包
リスト内包は、シーケンス型(リスト、ディクショナリ、タプル)からリストを生成する簡単な表記です。
よくある使い方としては、あるシーケンスの要素それぞれに何らかの処理を加えて
新しいシーケンスを生成したり、
ある条件にかなう要素のみを取り出してサブシーケンスを生成するという使い方があります。
#リストの要素を2倍にする >>> list = [1,2,3,4,5] >>> [v * 2 for v in list] [2, 4, 6, 8, 10] #リスト内の文字列の空白を削除する >>> fruitlist = [" banana ", " orange ", "apple "] >>> [fruit.strip() for fruit in fruitlist] ['banana', 'orange', 'apple'] #文字列にも適用可能である >>> moji = "hogefuga" >>> print [char for char in moji] ['h', 'o', 'g', 'e', 'f', 'u', 'g', 'a']
例外処理
文や式が構文的に正しい場合でも、実行しようとするとエラーが起きることがある。
実行中に検知されるエラーは例外と呼ばれるが、
これは必ずしも致命的なものではない。
pythonでは、予め起こりうる例外を予測し、例外に応じて処理を
書くことができる。
また、正しく例外を処理できた場合、エラーを抜けて
プログラムを続けることが可能である。
まずはソースコードから。
def devide(x, y): try: if(x == 0): raise NameError #(3) result = x / y except ZeroDivisionError: #(2) print"can't devide by zero" except NameError: #(3) print "NameError" except: print "Error" #(4) else: print "result = ",result #(1) finally: print if __name__ == "__main__": devide(2,1) #(1) devide(2,0) #(2) devide(0,2) #(3) devide('a','b') #(4)
プログラムの説明
-try節の中に例外が起こりえる処理を記述する。- except節で起きた例外に応じた処理を記述する。
- else節はtry節で例外が起きなかった場合に適用される。
- raiseは任意の例外をプログラマが呼び出したい時に用いる。
- finally節はtry節で例外が起こったかどうかに関わらず、適用される。後処理などを書くことが多い。
ぼくがかんがえたさいきょうのえでぃた
最近のメモ用途には、SublimeTextが最強だと思っています。(2014年1月5日更新)
SublimeText で Markdown
皆さん、エディタは普段のメモからプログラミングまで幅広く付き合っていると思います。
最近、僕は一番使いやすいエディタは何なのだろうと模索していました。
その結果、メモなど常用するためのエディタは、
KaoriYaさんのgvimが最強だという結論に至りました。
KaoriYa
http://www.kaoriya.net/
エディタといえば、
EmacsかViのどちらかですよね?
詳しくはWikipediaを見て下さい。
Wikipedia:エディタ戦争
僕は断然Vi派です。
というわけで、Viを基調にしたエディタを探していたのですが、
結局王道のKaoriYaさんのgvimを自分好みに最適化するという結論に至りました。
というわけで、今回は僕が自分好みに最適化した様をご紹介しようと思います。
そうです。僕の備忘録です。
本エントリーは3ステップになっております。
- vimrcの編集。
- カラースキームの変更。
- 簡単に表が書けるプラグインの導入。
それでは、順にご紹介します。
※注意
今回のエントリーはWindows版を対象としています。
Macの方は、
macvim-kaoriya
【Vim】Alt キーを Meta キーとして使う
を参考にして下さい。
また、ベースにMacVimを使用するので、vimrcやgvimrcの記述が若干異なります。
適宜読み替えて下さい。
以上に注意すれば、基本的に下記と同様の手順で設定できます。
vimrcの編集
これに関しては、僕のvimrcを見てもらうことが手っ取り早いですね。と言っても僕はvimrcを書けないので、他人のvimrcのいいとこ取りをしただけです。
"引用元 http://vimwiki.net/?vimrc%2F9 " URL: http://vim.wikia.com/wiki/Example_vimrc " Authors: http://vim.wikia.com/wiki/Vim_on_Freenode " Description: A minimal, but feature rich, example .vimrc. If you are a " newbie, basing your first .vimrc on this file is a good choice. " If you're a more advanced user, building your own .vimrc based " on this file is still a good idea. "------------------------------------------------------------ " Features {{{1 " " These options and commands enable some very useful features in Vim, that " no user should have to live without. " Set 'nocompatible' to ward off unexpected things that your distro might " have made, as well as sanely reset options when re-sourcing .vimrc " Vi互換モードをオフ(Vimの拡張機能を有効) set nocompatible " Attempt to determine the type of a file based on its name and possibly its " contents. Use this to allow intelligent auto-indenting for each filetype, " and for plugins that are filetype specific. " ファイル名と内容によってファイルタイプを判別し、ファイルタイププラグインを有効にする filetype indent plugin on " Enable syntax highlighting " 色づけをオン syntax on "------------------------------------------------------------ " Must have options {{{1 " " These are highly recommended options. " 強く推奨するオプション " One of the most important options to activate. Allows you to switch from an " unsaved buffer without saving it first. Also allows you to keep an undo " history for multiple files. Vim will complain if you try to quit without " saving, and swap files will keep you safe if your computer crashes. " バッファを保存しなくても他のバッファを表示できるようにする set hidden " Better command-line completion " コマンドライン補完を便利に set wildmenu " Show partial commands in the last line of the screen " タイプ途中のコマンドを画面最下行に表示 set showcmd " Highlight searches (use <C-L> to temporarily turn off highlighting; see the " mapping of <C-L> below) " 検索語を強調表示(<C-L>を押すと現在の強調表示を解除する) set hlsearch " Modelines have historically been a source of security vulnerabilities. As " such, it may be a good idea to disable them and use the securemodelines " script, <http://www.vim.org/scripts/script.php?script_id=1876>. " 歴史的にモードラインはセキュリティ上の脆弱性になっていたので、 " オフにして代わりに上記のsecuremodelinesスクリプトを使うとよい。 " set nomodeline "------------------------------------------------------------ " Usability options {{{1 " " These are options that users frequently set in their .vimrc. Some of them " change Vim's behaviour in ways which deviate from the true Vi way, but " which are considered to add usability. Which, if any, of these options to " use is very much a personal preference, but they are harmless. " Use case insensitive search, except when using capital letters " 検索時に大文字・小文字を区別しない。ただし、検索後に大文字小文字が " 混在しているときは区別する set ignorecase set smartcase " Allow backspacing over autoindent, line breaks and start of insert action " オートインデント、改行、インサートモード開始直後にバックスペースキーで " 削除できるようにする。 set backspace=indent,eol,start " When opening a new line and no filetype-specific indenting is enabled, keep " the same indent as the line you're currently on. Useful for READMEs, etc. " オートインデント set autoindent " Stop certain movements from always going to the first character of a line. " While this behaviour deviates from that of Vi, it does what most users " coming from other editors would expect. " 移動コマンドを使ったとき、行頭に移動しない set nostartofline " Display the cursor position on the last line of the screen or in the status " line of a window " 画面最下行にルーラーを表示する set ruler " Always display the status line, even if only one window is displayed " ステータスラインを常に表示する set laststatus=2 " Instead of failing a command because of unsaved changes, instead raise a " dialogue asking if you wish to save changed files. " バッファが変更されているとき、コマンドをエラーにするのでなく、保存する " かどうか確認を求める set confirm " Use visual bell instead of beeping when doing something wrong " ビープの代わりにビジュアルベル(画面フラッシュ)を使う set visualbell " And reset the terminal code for the visual bell. If visualbell is set, and " this line is also included, vim will neither flash nor beep. If visualbell " is unset, this does nothing. " そしてビジュアルベルも無効化する set t_vb= " Enable use of the mouse for all modes " 全モードでマウスを有効化 set mouse=a " Set the command window height to 2 lines, to avoid many cases of having to " "press <Enter> to continue" " コマンドラインの高さを2行に set cmdheight=2 " Display line numbers on the left " 行番号を表示 set number " Quickly time out on keycodes, but never time out on mappings " キーコードはすぐにタイムアウト。マッピングはタイムアウトしない set notimeout ttimeout ttimeoutlen=200 " Use <F11> to toggle between 'paste' and 'nopaste' " <F11>キーで'paste'と'nopaste'を切り替える set pastetoggle=<F11> "------------------------------------------------------------ " Indentation options {{{1 " インデント関連のオプション {{{1 " " Indentation settings according to personal preference. " Indentation settings for using 2 spaces instead of tabs. " Do not change 'tabstop' from its default value of 8 with this setup. " タブ文字の代わりにスペース2個を使う場合の設定。 " この場合、'tabstop'はデフォルトの8から変えない。 set shiftwidth=2 set softtabstop=2 set expandtab " Indentation settings for using hard tabs for indent. Display tabs as " two characters wide. " インデントにハードタブを使う場合の設定。 " タブ文字を2文字分の幅で表示する。 "set shiftwidth=2 "set tabstop=2 "------------------------------------------------------------ " Mappings {{{1 " マッピング " " Useful mappings " Map Y to act like D and C, i.e. to yank until EOL, rather than act as yy, " which is the default " Yの動作をDやCと同じにする map Y y$ " Map <C-L> (redraw screen) to also turn off search highlighting until the " next search " <C-L>で検索後の強調表示を解除する nnoremap <C-L> :nohl<CR><C-L> "------------------------------------------------------------ "引用元 http://gravity-crim.blogspot.jp/2011/06/vimemacs-2_20.html " インサートモード時の Emacs キーバインド " inoremap <C-p> <Up> inoremap <C-n> <Down> inoremap <C-b> <Left> inoremap <C-f> <Right> inoremap <C-e> <End> inoremap <C-a> <Home> inoremap <C-h> <Backspace> inoremap <C-d> <Del> " カーソル位置の行をウィンドウの中央に来るようにスルロール inoremap <C-l> <C-o>zz " カーソル以前の文字を削除 inoremap <C-u> <C-o>d0 " カーソル以降の文字を削除 inoremap <C-k> <C-o>D " アンドゥ inoremap <C-x>u <C-o>u " 貼りつけ inoremap <C-y> <C-o>P " カーソルから単語末尾まで削除 inoremap <F1>d <C-o>dw " ファイルの先頭に移動 inoremap <F1>< <Esc>ggI " ファイルの末尾に移動 inoremap <F1>> <Esc>GA " 下にスクロール inoremap <C-v> <C-o><C-f> " 上にスクロール inoremap <F1>v <C-o><C-b> " Ctrl-Space で補完 " Windowsは <Nul>でなく <C-Space> とする "inoremap <Nul> <C-n> inoremap <C-Space> <C-n> "sonoshoou start inoremap { {}<LEFT> inoremap [ []<LEFT> inoremap ( ()<LEFT> inoremap " ""<LEFT> inoremap ' ''<LEFT> inoremap <A--> -------------------------------------------------- inoremap <A-=> ================================================== inoremap <A-.> <ESC>i+<ESC>V>$a inoremap <A-,> <ESC>i-<ESC>V>>$a inoremap <A-/> =><ESC>V>$a inoremap <A-0> 0. inoremap <A-1> 1. inoremap <A-2> 2. inoremap <A-3> 3. inoremap <A-4> 4. inoremap <A-5> 5. inoremap <A-6> 6. inoremap <A-7> 7. inoremap <A-8> 8. inoremap <A-9> 9. inoremap <S-ENTER> <ESC>o<SPACE><LEFT><DELETE> "ファイルの保存" inoremap <C-x>s <ESC>:w<ENTER>i "ファイルを閉じる" inoremap <C-x>k <ESC>:q<ENTER> "全て選択" inoremap <C-x>h <ESC>ggVG "改行コード表示" set list "sonoshou end "クリップボード共有" set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8Pt clipboard=unnamed set fileencodings=iso-2022-jp,utf-8,cp932,euc-jp,default,lati "タブモード "http://www.mk-mode.com/wordpress/2012/06/04002036/ ":tabn(:tabnext) 右となりのタブへ移動 ":tabc(:tabclose) 今いるタブを閉じる ":tabe(:tabedit) 新しいタブを開く set showtabline=2 "日本語入力固定モード "https://sites.google.com/site/fudist/Home/vim-nihongo-ban/vim-japanese/ime-control#statusline " 「日本語入力固定モード」がオンの場合、ステータス行にメッセージ表示 set statusline+=%{IMStatus('[日本語固定]')} " im_control.vimがない環境でもエラーを出さないためのダミー関数 function! IMStatus(...) return '' endfunction "バックアップファイルとスワップファイルの設定 "どちらも生成しない。 "http://d.hatena.ne.jp/RKTM/20070825/1188065053 set nobackup set noswapfile
今はこんな感じですが、適宜変えていきそうです。
カラースキームの変更
デフォルトのエディタのカラースキームが気に食わなかったので、変更しました。数あるカラースキームからwombatを選びました。
下の方に画像を掲載しました。
(半透明の)黒地に白文字でなかなか見やすいです。
wombat
http://www.vim.org/scripts/script.php?script_id=1778
このファイルをダウンロードして、
vim/runtime/colors/ or vim/colors/
の中にwombat.vimを入れ込みます。
※ダウンロードしたバージョンによって場所が異なるのかもしれません。
(私の思い違いの可能性もあります。)
colorsフォルダを適宜捜してみてください。
そして、gvimrcに
"--------------------------------------------------------------------------- " カラー設定: "colorscheme morning colorscheme wombat " Copyright (C) 2011 KaoriYa/MURAOKA Taro "独自に見た目を設定 set guioptions-=T " ツールバーを非表示 set lines=60 columns=100 " 初期画面のサイズ設定 gui set transparency=240 " ウインドウを半透明に" カラー設定: "colorscheme morning "---------------------------------------------------------------------------
と該当箇所に入力すれば設定完了です。
参考URL:http://qiita.com/items/89c6c983732a4ed26e1a
うまく設定できていると以下のようになります。
ね?テンション上がったでしょ?
簡単に表が書けるプラグインの導入
エディタで表を書きたい時ってありますよね。ただ、そういうときわざわざ空白文字やらタブやらで見やすいように
文字を整形するのは面倒。
そんな方は
高性能なテキスト整形ツールAlign
をインストールしましょう。
- http://www.vim.org/scripts/script.php?script_id=294のAlign.vba.gzをダウンロード。
- ダウンロードしたファイルを解凍する。
- vimで解凍されたAlign.vbaを開く。
- 「:so %」と打ち込む。
以上です。
以下のサイトからほぼ引用しました。
インストール方法や使い方の詳細等は以下のサイトが詳しいです。
高性能なテキスト整形ツールAlignの使い方 名無しのvim使い
日本語の入力の切り替え
インストール時の設定ですと、日本語でvimを使おうとすると、なかなか使いづらいです。
以下のページでお勉強しましょう。
上記のページを参考に、僕が行った設定を紹介。
<インストール方法>
1.ページ内のim_control.vimをダウンロード
2.m_control.vimを .vim/plugin (vimfiles/plugin)などランタイムパスの通った場所にコピー
以上です。
<使い方>
挿入モード時、<C-^>でIMEを切り替え。
簡単ですが、これでかなり使いやすくなるはずです。
eclipse vim風
vimmerのあなたへ。
eclipseをvim風のキーバインドに変更するプラグインの紹介です。
英語版をお使いの方は、適宜読み替えて下さい。
1.Eclipseを起動する。
2.ヘルプ → 新規ソフトウェアのインストール
3.「追加」を押す。
4.名前:Vrapper ロケーション:http://vrapper.sourceforge.net/update-site/stable/ を入力
5.「すべて選択」を押す。
6.「次へ」
あとは流れでいけるはずです。
使い方等は下記のサイトが詳しいので、合わせてご参照下さい。
Eclipseのキーバインドをvim風にできるVrapperが素晴らしすぎる件について -ゆるよろ日記-
http://yuroyoro.hatenablog.com/entry/20100218/1266477264
python復習まとめ4
モジュールの例
フィボナッチ数列の文字列から、モジュールについて学ぶ。#fibo.pyの中身 def fib(n): a ,b = 0, 1 while b < n: print b, a, b = b, a+b print if __name__ == "__main__": import sys fib(int(sys.argv[1]))
- モジュールとして使う。
- モジュールをスクリプトとして実行する。
以上の2通りの例を示す。
#モジュールとして使う。 >>> import fibo >>> fibo.fib(10) 1 1 2 3 5 8 #モジュールとして使う。 #(ただし、可動性が乏しくなるため、あまり推奨されない。) >>> from fibo import * >>> fib(10) 1 1 2 3 5 8 #モジュールをスクリプトとして実行する。 #(コンソール上から起動。) >python fibo.py 10 1 1 2 3 5 8
コンソールから呼ばれた場合は、
if __name__ == "__main__":
の中身が走ることとなる。
クラスについて
基本的なクラスを理解するためのテストモジュールを作成した。非常に見づらくなってしまったのは、私の復習用だからということにしよう……。
クラスメソッド、インスタンスメソッドを呼び出す時、
呼び出し元のインスタンスもselfとして引数に与えられるが特徴的である。
そのため、メソッドの初めの引数はselfにすることが推奨されている。
import math class MyPoint: num = 0 #initialize def __init__(self, x, y): MyPoint.num += 1 self.id = MyPoint.num self.x = x self.y = y def distance(self,point): result = math.sqrt(math.pow(self.x - point.x, 2) + math.pow(self.y - point.y, 2)) return result @classmethod #error if you don't use decorator def initNum(self): MyPoint.num = 0 if __name__ == "__main__": #create list classList = [] classList.append(MyPoint(0,1)) classList.append(MyPoint(2,0)) #output list and output instance var for v in classList: print 'id =',v.id, 'x =',v.x, 'y =',v.y #output class var print 'MyPoint Num =',MyPoint.num #test instance method print 'Distance =',classList[0].distance(classList[1]) #test class method MyPoint.initNum() print 'MyPoint Num =',MyPoint.num
クラス継承について
pythonは多重継承をサポートする。
ただし、多重継承はプログラムが複雑になりやすいので、推奨はされない。
また、一般的なオブジェクト指向言語は変数とメソッドの両方が継承されるが、
pythonでは、メソッドとクラス変数は継承されるが、インスタンス変数は継承されない。
従って、pythonでは、インスタンス変数を継承するために明示的にプログラムを書く必要がある。
class Hoge: def __init__(self, x, y): self.x = x self.y = y def get_x(self): return x def get_y(self): return y class Fuga: def __init__(self, z): self.z = z def get_z(self): return z class HogeFuga(Hoge,Fuga): def __init__(self, x, y, z): Hoge.x = x Hoge.y = y Fuga.z = z if __name__ == "__main__": hogefuga = HogeFuga(1, 2, 3) print hogefuga.x print hogefuga.z
python復習まとめ3
リストについて
リストオブジェクトのメソッドを以下に示す。append(x)
リストの末尾にアイテムを1つ追加する。a[len(a):] = [x]と等価。
extend(L)
リストの末尾に、与えられたリストLの全アイテムを追加することで、リストを延長する。a[len(a):] = Lと等価。
insert(i, x)
指定された位置にアイテムを挿入する。第1引数は要素のインデックスで、挿入はこの要素の前に行われる。remove(x)
値がxである最初のアイテムを削除する。そのようなアイテムが存在しなければエラーとなる。pop([i])
指定された位置のアイテムをリストから削除し、このアイテムを返す。インデックスが指定されていないと、a.pop()はリストの最後のアイテムを返し、リストから削除する。index(x)
値がxである最初のアイテムのインデックスを返す。そのようなアイテムが存在しなければエラーとなる。sort()
リストをソートする。remove()
リストを逆順にソートする。リストをスタックとして使う
>>> stack = [1,2,3] >>> stack.append(4) >>> stack [1, 2, 3, 4] >>> stack.pop() 4 >>> stack [1, 2, 3]
リストをキュートして使う
>>> queue = [1,2,3] >>> queue.append(4) >>> queue [1, 2, 3, 4] >>> queue.pop(0) 1 >>> queue [2, 3, 4]
del文
>>> a = [1,2,3,4,5] >>> del a[2] >>> a [1, 2, 4, 5] >>> del a[2:] >>> a [1, 2]
タプル
複数の要素から構成され、それを一つの値として扱える機能。リストとの違いは、値の変更が出来るか出来ないという点である。
>>> t = (1,'a',l) >>> t (1, 'a', [1, 2, 3]) >>> t = 1,'a',l >>> t (1, 'a', [1, 2, 3]) >>> t = () >>> t () >>> t = 'a', >>> t ('a',)
集合(set)
集合とは、重複しない要素を順不同で集めたものである。基本的な要としては存在判定や、重複エントリの排除などがある。
また、和、交差、差などの数学的演算をサポートしている。
>>> basket = {'apple', 'orange', 'grape'} >>> bascket Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'bascket' is not defined >>> basket set(['orange', 'grape', 'apple']) >>> basket = {'apple','orange','orange','grape','apple'} >>> basket set(['orange', 'grape', 'apple']) >>> 'banana' in basket False >>> basket & os #共通する要素 set(['apple']) >>> basket | os #前者または後者に存在する要素 set(['orange', 'windows', 'grape', 'apple']) >>> basket - os #前者には存在し、後者に存在しない要素 set(['orange', 'grape']) >>> basket ^ os #前者または後者に存在し、重複を除いた要素 set(['windows', 'orange', 'grape'])
ディクショナリ
シーケンスには連続した数字によるインデックスが付いているのに対し、ディクショナリにはキーによるインデックスが付いている。キーには文字列や数値などが扱える。
ディクショナリは他の言語では、「連想配列」や「ハッシュ」として存在することがある。
>>> tel = {'taro':1234, 'hanako':5678} >>> tel {'hanako': 5678, 'taro': 1234} >>> tel['taro'] 1234 >>> del tel['hanako'] #要素の削除 >>> tel {'taro': 1234} >>> tel['ichiro'] = 2345 #要素の追加 >>> tel {'ichiro': 2345, 'taro': 1234} >>> list(tel.keys()) ['ichiro', 'taro'] >>> sorted(tel.values()) [1234, 2345] >>> 'jack' in tel False #ループのテクニック >>> tel.items() [('ichiro', 2345), ('taro', 1234)] >>> for k ,v in tel.items(): ... print(k, v) ... ('ichiro', 2345) ('taro', 1234) >>> for i, v in enumerate(tel.values()): ... print(i, v) ... (0, 2345) (1, 1234) <|| *1347957607*[python][プログラミング]python復習まとめ2 <h2>if文</h2> >|python| >>> x = 3 >>> if x < 2: ... print("a") ... elif x == 2: ... print("b") ... else: ... print("c")
for文
>>> a = ['cat', 'dog', 'bird'] >>> for x in a: ... print(x, len(x)) ('cat', 3) ('dog', 3) ('bird', 4) >>> for i in range(len(a)): ... print(i, a[i]) ... (0, 'cat') (1, 'dog') (2, 'bird')
while文
>>> a, b = 0, 1 >>> while b < 10: ... print b, ... a, b = b, a + b ... 1 1 2 3 5 8
その他の制御構文
break文
breakを囲うもっとも小さなforまたはwhileのループを抜ける。他の言語のbreak文と大差はない。
continue文
continueを囲うループの残りの処理を飛ばして次回の反復へ進む。他の言語のcontunie文と大差はない。
pass文
pass文は、構文的に文が必要ではあるが、プログラム的には何もする必要がないときに使う。また、新しくコードを描いている時関数や条件の本体にプレースホルダとして置いておき、抽象的なレベルで考え続けたいときに用いる。
>>> while True: ... pass >>> class MyEmptyClass: ... pass >>> def initlog(): ... pass #あとで実装する
関数定義
#引数がない関数 >>> def test(): ... print "test" ... >>> test() test #引数がある関数 初期値を与えることも可能。 >>> def test2(a, b, op=1): ... if op == 1: ... print a + b ... else: ... print a - b ... >>> test2(1,2) 3 >>> test2(1,2,2) -1 #引数がある関数 二つ変数を返すことも可能。 >>> def test3(a,b): ... return a+1, b+1 ... >>> x, y = test3(1,2) >>> x 2 >>> y 3
python復習まとめ1
pythonについて忘れてきたので復習。
やらなくなるとすぐ忘れてしまう……。
四則演算+α
>>> a = b = 2 #同時に代入可能。 >>> x , y = 2 , 3 #別の値も同時に代入可能。 >>> a+b 4 >>> 8/5 #切り捨てない。 1.6 >>> 7//3 #切り捨てるには//を使う。 2 >>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5
文字列
>>> str = 'abc' >>> str[1] 'b' >>> str[1:3] #2文字目から3文字目。 'bc' >>> str[-1] #最後の文字。 'c' >>> str[:2] #2文字目まで 'ab' >>> str[2:] #2文字目より後の文字。 'c' >>> str[-2:] #最後の2文字目より後の文字。 'bc' >>> 'xyz' + str 'xyzabc >>> len(str) 3
まとめると、以下の関係が成り立つ。 +---+---+---+ | a | b | c | +---+---+---+ 0 1 2 3 -3 -2 -1
リスト
リストは、角括弧の中にカンマ区切りの値を入力することで定義できる。リストのアイテムがすべて同じ型である必要はない。
>>> a = ['apple', 'orange', 13, 34.5] >>> a[1:-1] ['orange', 13] >>> 2*a ['apple', 'orange', 13, 34.5, 'apple', 'orange', 13, 34.5] >>> a[:2] + ['grape'] ['apple', 'orange', 'grape'] >>> a[2] += 2 >>> a ['apple', 'orange', 15, 34.5] >>> a[0:2] = [2,4] >>> a [2, 4, 15, 34.5] >>> a[0:2] = [] >>> a [15, 34.5] >>> a[1:1] = ['yes', 'no'] >>> a [15, 'yes', 'no', 34.5] >>> a[1] = ['great','good'] >>> a [15, ['great', 'good'], 'no', 34.5] >>> a[1] ['great', 'good'] >>> a[1][0] 'great' >>> a[1].append('nice') >>> a [15, ['great', 'good', 'nice'], 'no', 34.5] >>> len(a) 4 >>> a[:] = [] >>> a []