<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Yukun&#039;s Blog &#187; Python</title>
	<atom:link href="http://www.yukun.info/blog/tag/python/feed" rel="self" type="application/rss+xml" />
	<link>http://www.yukun.info</link>
	<description>難しいことは分かりやすく、簡単なことは面白く紹介</description>
	<lastBuildDate>Thu, 26 Jan 2012 03:33:59 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Python Twitter のインストール</title>
		<link>http://www.yukun.info/blog/2011/03/python-twitter-install.html</link>
		<comments>http://www.yukun.info/blog/2011/03/python-twitter-install.html#comments</comments>
		<pubDate>Sat, 05 Mar 2011 13:55:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Setting]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1865</guid>
		<description><![CDATA[Twitter APIのPython ラッパーライブラリのインストール手順を以下に紹介。 実行環境は以下の通り。 OS ：Windows7 Pythonの実行パス ：C:\Python27 ダウンロードするもの pyth &#8230; <a href="http://www.yukun.info/blog/2011/03/python-twitter-install.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2011/03/python-twitter-install.html">Python Twitter のインストール</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Twitter APIのPython ラッパーライブラリのインストール手順を以下に紹介。</p>
<p>実行環境は以下の通り。<br />
OS				：Windows7<br />
Pythonの実行パス	：C:\Python27</p>
<h3>ダウンロードするもの</h3>
<h4>python-twitter ライブラリ</h4>
<p><a href="http://code.google.com/p/python-twitter/">http://code.google.com/p/python-twitter/</a></p>
<p><span id="more-1865"></span></p>
<h4>依存ライブラリ</h4>
<ol>
<li><a href="http://cheeseshop.python.org/pypi/simplejson">http://cheeseshop.python.org/pypi/simplejson</a></li>
<li><a href="http://code.google.com/p/httplib2/">http://code.google.com/p/httplib2/ </a></li>
<li><a href="http://github.com/simplegeo/python-oauth2">http://github.com/simplegeo/python-oauth2</a></li>
</ol>
<h3>インストール手順</h3>
<p>まず、依存ライブラリをインストールする。それぞれ解凍したフォルダ上で以下のコマンドを実行</p>
<pre>
C:\httplib2-0.6.0>python setup.py install

C:\simplejson-2.1.3>python setup.py install

C:\simplegeo-python-oauth2-1920657>python setup.py install
</pre>
<p>為念、import を実行しインストールの確認を取る。</p>
<pre>
>>> import httplib2
>>> import simplejson
>>> import oauth2
</pre>
<p>最後に、python-twitter ライブラリをインストールする。</p>
<pre>
C:\python-twitter-0.8.1>python setup.py build
C:\python-twitter-0.8.1>python setup.py install
</pre>
<h3>サンプルプログラム</h3>
<p>指定のユーザの発言(@応答は除く)を表示するスクリプトを紹介。</p>
<h4>ソースコード</h4>
<p>
<pre>
import twitter

api = twitter.Api()
statuses = api.GetUserTimeline('yukun_')
for s in statuses:
	if s.text[0] != '@':
		print s.text , "|" , s.created_at
</pre>
</p>
<h4>実行結果</h4>
<pre>

お知らせ: ブログ更新しました。「 VMware PlayerでCentOSを導入 」 - http://tinyurl.com/4aqjpyf | Wed Feb 23 14:52:48 +0000 2011
I uploaded a YouTube video -- カードゲームアプリの作成 (1)画像のD&#038;D http://youtu.be/QSn7gsmY1iQ?a | Sun Feb 13 11:00:05 +0000 2011
お知らせ: ブログ更新しました。「 Shell Script: testコマンドによる条件判定 (数値、文字列) 」 - http://tinyurl.com/5tbr7va | Sun Feb 13 07:01:06 +0000 2011
お知らせ: ブログ更新しました。「 Java: TCP Socket Echo Server/Client サンプル 」 - http://tinyurl.com/4seszhb | Fri Feb 11 22:31:19 +0000 2011
今日は品川でボルダリングしてきた。面白かったー(^o^) | Fri Feb 11 13:40:43 +0000 2011
お知らせ: ブログ更新しました。「 Subversion: コトハジメ 」 - http://tinyurl.com/4tq457t | Mon Feb 07 12:01:04 +0000 2011
お知らせ: ブログ更新しました。「 Shell Script: for文 - ワードリストに変数、コマンドを使用 」 - http://tinyurl.com/4hhw3n8 | Sun Feb 06 11:00:49 +0000 2011
お知らせ: ブログ更新しました。「 Shell Script: for文 - ワードリストを順に出力 」 - http://tinyurl.com/4zjewru | Sun Jan 30 13:47:35 +0000 2011
運転免許を更新中(=´∇｀=) | Sun Jan 30 04:33:30 +0000 2011
デフォルトテーマ(Twenty Ten)が地味に優秀。 CSS がひとつに纏まっているのでページ読み込みが多少早くなった。 | Mon Jan 17 14:03:52 +0000 2011
WordpressのVer3テーマへの移行テストが完了したが、ユーザービリティの影響が不明瞭で中々踏み切れない。アクセス数がもっと安定してきたらやろうかな～。 | Mon Jan 03 08:02:15 +0000 2011
New blog posting, PHP: 添字配列の初期化、出力、代入 - http://tinyurl.com/2ax2e2h | Mon Jan 03 07:06:40 +0000 2011
情報セキュリティスペシャリスト試験に受かりましたー。 | Mon Dec 20 13:12:15 +0000 2010
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/install-lxml.html" rel="bookmark" title="2008年6月13日">Python: lxmlのインストール方法</a></li>
<li><a href="http://www.yukun.info/blog/2009/01/learning-english-with-twitter.html" rel="bookmark" title="2009年1月4日">Twitterを英語の学習ツールにしてみる</a></li>
<li><a href="http://www.yukun.info/blog/2011/02/vmware-player-centos.html" rel="bookmark" title="2011年2月23日">VMware PlayerでCentOSをインストール</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-set-list-comparison.html" rel="bookmark" title="2008年8月7日">Python: set型の集合演算で2つのリスト要素を比較</a></li>
<li><a href="http://www.yukun.info/blog/2011/12/linux-redmine-subversion-install.html" rel="bookmark" title="2011年12月6日">Linux: RedmineとSubversionのインストール・設定例</a></li>
</ul>
<p><!-- Similar Posts took 8.284 ms --></p>
<p><a href="http://www.yukun.info/blog/2011/03/python-twitter-install.html">Python Twitter のインストール</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2011/03/python-twitter-install.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</title>
		<link>http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html</link>
		<comments>http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html#comments</comments>
		<pubDate>Thu, 18 Sep 2008 11:40:50 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1191</guid>
		<description><![CDATA[ファイルのパスや名前のミス、パーミッションの権限が無い等が原因でファイルを読み込めない場合があります。そのような場合、すなわち例外が発生した際にそこで処理を中断して、発生した例外に合わせた処理ブロックにジャンプする構文が &#8230; <a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>ファイルのパスや名前のミス、パーミッションの権限が無い等が原因でファイルを読み込めない場合があります。そのような場合、すなわち例外が発生した際にそこで処理を中断して、発生した例外に合わせた処理ブロックにジャンプする構文が、try:～except Error:～構文です。</p>
<p>今回は、コマンドライン引数で英文テキストファイル名を指定し、スクリプト内でファイル内容を読み込み、単語数をカウントし出力するスクリプトを以って、オプションのelse、finallyブロックを含めた例外ブロックの扱いを確認します。<br />
ただし、ここでの「単語」とは、１つの空白文字で区切られた文字列とします（簡単に）。</p>
<h2>ソースコード</h2>
<pre>
# -*- coding: UTF-8 -*-

import sys

script_name = sys.argv[0]
try:
    arg = sys.argv[1]
    f = open(arg, 'r')
except IndexError:
    print 'Usage: %s TEXTFILE' % script_name
except IOError:
    print '"%s" cannot be opened.' % arg
else:
    print arg, 'contains', len(f.read().split(' ')), 'words.'
    f.close()
finally:
    print 'n"%s" process end.' % script_name
    quit()
print 'Not reach this line.'
</pre>
<h2>コードの説明</h2>
<h3>tryブロック</h3>
<p>まず、例外を発生させる恐れのある行は、tryブロック内に書きます。</p>
<p>ここで発生しそうなのは、コマンドライン引数が格納されているリストへのアクセス部分であるsys.argv[1]です。[]演算子で存在しない要素を参照するエラー、もとい例外が発生する恐れがあります。</p>
<p>また、ファイルを開くopen(arg, &#8216;r&#8217;)も冒頭の理由で例外を発生させるかもしれません。</p>
<h3>exceptブロック</h3>
<p>exceptブロックは、tryブロックで例外が発生した場合にのみ実行されるブロックです。その為、例外が発生しない場合は実行されません。</p>
<p>発生する可能性のある例外のタイプ毎にexceptブロックを書けば、そのタイプ毎の例外への対処処理を書くことが出来ます。</p>
<pre>
except <em>TYPE_A</em>Error:
    <em>TYPE_A</em>Errorが発生した際のとある処理...
except <em>TYPE_B</em>Error:
    <em>TYPE_B</em>Errorが発生した際のとある処理...
</pre>
<h3>elseブロック　（オプション）</h3>
<p>elseブロックは全てのexceptブロックの後に書きます（任意なので書かなくても構わない）。</p>
<p>elseブロックはtryブロックで例外が発生<strong>しなかった場合にのみ</strong>実行されるブロックです。今回は、ファイルの読み込みとクローズに使用しています。</p>
<h3>finallyブロック　（オプション）</h3>
<p>finallyブロックはtryブロックで例外が発生<strong>するしないに関わらず</strong>実行されるブロックです（任意なので書かなくても構わない）。</p>
<h2>実行結果</h2>
<p>読み込むテキストファイルを以下の<em>aLine.txt</em>とします。<br />
<em>aLine.txt</em></p>
<pre>
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
</pre>
<h3>コマンドラインで適切な引数を与えた場合</h3>
<pre>
$ python excp01.py aLine.txt
aLine.txt contains 22 words.

"excp01.py" process end.
</pre>
<h3>存在しないファイル名を引数を与えた場合</h3>
<pre>
$ python excp01.py texfile.tex
"texfile.tex" cannot be opened.

"excp01.py" process end.
</pre>
<h3>コマンドライン引数を与えなかった場合</h3>
<pre>
$ python excp01.py
Usage: excp01.py TEXTFILE

"excp01.py" process end.
</pre>
<h2>例外オブジェクト名をpython処理系に聞いてみる</h2>
<p>どんなメソッドや関数、演算子が、どのような例外を投げるのか予測が付かない場合があるかと思います。<br />
そんな場合でもとりあえずスクリプトを実行してエラーを確認してみましょう。<br />
<code>SyntaxError: invalid syntax</code>以外のエラーがある場合、例えば、</p>
<pre>
$ python excp01.py
Traceback (most recent call last):
  File "excp01.py", line 5, in <module>
    arg = sys.argv[1]
IndexError: list index out of range
</pre>
<p>のような場合は、最終行の行頭のIndexErrorが例外名となります。</p>
<h2>何でも例外任せにしていいの？</h2>
<p>計算量からみてあまり良いとは言えません。今プログラムのコマンドライン引数の確認を、<br />
<code>if len(sys.argv) != 2: ホニャララ</code><br />
とすると整数の比較ですみますが、例外のキャッチに任せると、例外インスタンスを生成し送出するという、結構な計算量がかかります。ネットワーク接続やファイル読み書きなどのIOでは有効ですが、それ以外では積極的に使わないほうがいいかもしれません。</p>
<h2>ドキュメント</h2>
<ul>
<li><a href="http://docs.python.org/lib/module-exceptions.html" title="2.3 Built-in Exceptions" target="_blank">2.3 Built-in Exceptions</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html" rel="bookmark" title="2008年8月9日">Python: 指定したパスのディレクトリ中のファイル一覧を出力</a></li>
</ul>
<p><!-- Similar Posts took 13.034 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: テキストファイルの行頭に行番号を追加</title>
		<link>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html</link>
		<comments>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html#comments</comments>
		<pubDate>Mon, 08 Sep 2008 12:50:42 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[read]]></category>
		<category><![CDATA[write]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1017</guid>
		<description><![CDATA[コマンドラインで指定されたテキストファイルの行頭に行番号を追加し、そのデータを新たなファイルに書き出すスクリプトです。 ソースコード #!/usr/bin/python # coding: UTF-8 import sy &#8230; <a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Python: テキストファイルの行頭に行番号を追加</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>コマンドラインで指定されたテキストファイルの行頭に行番号を追加し、そのデータを新たなファイルに書き出すスクリプトです。</p>
<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

import sys

argvs = sys.argv
argc = len(argvs)
if (argc != 3):
    print 'Usage: $ python %s target_file making_file' % argvs[0]
    quit()
f = open(argvs[1])
lines2 = f.readlines()
f.close()
nf = open(argvs[2], 'w')
i = 1
for line in lines2:
    nf.write('%3d: %s' % (i, line))
    i = i + 1
nf.close()
</pre>
<p>仮にこのソースコードをfile05a.pyというファイルで保存した場合、使用する際はプロンプトに以下のように打ち込みます。</p>
<h3>実行結果</h3>
<h4>プロンプト</h4>
<pre>
> python file05a.py file05a.py file05a-l.txt
</pre>
<p>この結果、生成されたファイルが下記になります。</p>
<h4>file05a-l.txt</h4>
<pre>
  1: #!/usr/bin/python
  2: # coding: UTF-8
  3:
  4: import sys
  5:
  6: argvs = sys.argv
  7: argc = len(argvs)
  8: if (argc != 3):
  9:     print 'Usage: $ python %s target_file making_file' % argvs[0]
 10:     quit()
 11: f = open(argvs[1])
 12: lines2 = f.readlines()
 13: f.close()
 14: nf = open(argvs[2], 'w')
 15: i = 1
 16: for line in lines2:
 17:     nf.write('%3d: %s' % (i, line))
 18:     i = i + 1
 19: nf.close()
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html" rel="bookmark" title="2008年9月6日">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html" rel="bookmark" title="2008年9月18日">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a></li>
</ul>
<p><!-- Similar Posts took 7.135 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Python: テキストファイルの行頭に行番号を追加</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</title>
		<link>http://www.yukun.info/blog/2008/09/python-file-write-writelines.html</link>
		<comments>http://www.yukun.info/blog/2008/09/python-file-write-writelines.html#comments</comments>
		<pubDate>Sat, 06 Sep 2008 12:50:16 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[write]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=817</guid>
		<description><![CDATA[テキストファイルへの書き込み処理をFileオブジェクトの以下のメソッドを用いて書いてみます。 write() &#8211; 文字列を引数に取り、ファイルに書き込む。 writelines() &#8211; シーケンス &#8230; <a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>テキストファイルへの書き込み処理をFileオブジェクトの以下のメソッドを用いて書いてみます。</p>
<ul>
<li>write() &#8211; 文字列を引数に取り、ファイルに書き込む。</li>
<li>writelines() &#8211; シーケンス型を引数に取り、ファイルに書き込む。</li>
</ul>
<h2>write() &#8211; 文字列を引数に取り、ファイルに書き込む</h2>
<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

# 書き込む文字列
str = """It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on."""

f = open('text.txt', 'w') # 書き込みモードで開く
f.write(str) # 引数の文字列をファイルに書き込む
f.close() # ファイルを閉じる
</pre>
<h3>実行結果</h3>
<p><em>text.txt</em></p>
<pre>
It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
</pre>
<h2>writelines() &#8211; シーケンス型を引数に取り、ファイルに書き込む</h2>
<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

str = """It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on."""
strs = str.split('n') # 一行が一要素(文字列)のリスト

f = open('text.txt', 'w') # 書き込みモードで開く
f.writelines(strs) # シーケンスが引数。
f.close()
</pre>
<h3>実行結果</h3>
<p><em>text.txt</em></p>
<pre>
It is meaningless only to think my long further aims idly.It is important to set my aims but at the same time I should confirm my present condition.Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
</pre>
<p>書き込む際は、シーケンスの各要素の文字列を単に連結するだけです。間には改行も空白文字も含まれません。</p>
<p>そういえば、csv.writerオブジェクトを用いたCSVファイル書き込みにはlineterminatorオプション引数に、任意の連結文字列(言い方よくないね→行の終端文字)を代入できます。主に、環境に合わせた改行文字を代入するのに使います。→<a href="http://www.yukun.info/blog/2008/06/python-csv-write.html" title="Python: CSVファイルに書き込み - csv.writerオブジェクト - Yukun's Blog">Python: CSVファイルに書き込み &#8211; csv.writerオブジェクト</a></p>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/built-in-funcs.html" title="2.1 Built-in Functions" target="_blank">2.1 Built-in Functions</a></li>
<li><a href="http://docs.python.org/lib/bltin-file-objects.html" title="3.9 File Objects" target="_blank">3.9 File Objects</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html" rel="bookmark" title="2008年12月18日">AIR: テキストファイルに書き込み &#8211; openAsync()、writeMultiByte()</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-write.html" rel="bookmark" title="2008年6月18日">Python: CSVファイルに書き込み &#8211; csv.writerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
</ul>
<p><!-- Similar Posts took 8.312 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/python-file-write-writelines.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: 二値の交換</title>
		<link>http://www.yukun.info/blog/2008/08/python-change-two-value.html</link>
		<comments>http://www.yukun.info/blog/2008/08/python-change-two-value.html#comments</comments>
		<pubDate>Wed, 27 Aug 2008 15:00:53 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[List]]></category>

		<guid isPermaLink="false">http://blog.yukun.info/?p=548</guid>
		<description><![CDATA[ソート系のアルゴリズムを実装する際などに、配列の任意の2つの要素を交換する処理が必要な場合がありますので、以下にその手順の一例を示します。 ソースコード # coding: UTF-8 a = [10, 20] prin &#8230; <a href="http://www.yukun.info/blog/2008/08/python-change-two-value.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/08/python-change-two-value.html">Python: 二値の交換</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>ソート系のアルゴリズムを実装する際などに、<em>配列の任意の2つの要素を交換する</em>処理が必要な場合がありますので、以下にその手順の一例を示します。</p>
<h3>ソースコード</h3>
<pre>
# coding: UTF-8

a = [10, 20]
print '%d %d' % (a[0], a[1])
a[0], a[1] = a[1], a[0]
print '%d %d' % (a[0], a[1])
</pre>
<h3>実行結果</h3>
<pre>
10 20
20 10
</pre>
<p>何だかperlの多重代入を思い出します。<br />
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/08/python-sequence-list.html" rel="bookmark" title="2008年8月5日">Python: リストの上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-upper-lower-case-letters-converted.html" rel="bookmark" title="2008年8月3日">Python: リスト中の文字列を大文字⇔小文字に変換</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list.html" rel="bookmark" title="2008年6月1日">Python: リストの初期化・出力・代入・要素数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list2.html" rel="bookmark" title="2008年6月12日">Python: リストの要素の追加と削除、取出し &#8211; append()、extend()、pop()、remove()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-sequence.html" rel="bookmark" title="2008年6月2日">Python: リストの抽出・連結・要素の追加</a></li>
</ul>
<p><!-- Similar Posts took 17.356 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/08/python-change-two-value.html">Python: 二値の交換</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/08/python-change-two-value.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python: 指定したパスのディレクトリ中のファイル一覧を出力</title>
		<link>http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html</link>
		<comments>http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html#comments</comments>
		<pubDate>Fri, 08 Aug 2008 15:00:19 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://blog.yukun.info/?p=424</guid>
		<description><![CDATA[あるディレクトリから特定のファイルを検索したい場合、探索対象ディレクトリ内のファイルを全て取得する必要があります。今回は、引数にディレクトリを指すパスを指定することによって、そのディレクトリの内容を取得する関数を2つ示し &#8230; <a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html">Python: 指定したパスのディレクトリ中のファイル一覧を出力</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>あるディレクトリから特定のファイルを検索したい場合、探索対象ディレクトリ内のファイルを全て取得する必要があります。今回は、引数にディレクトリを指すパスを指定することによって、そのディレクトリの内容を取得する関数を2つ示します。</p>
<h3>ソースコード</h3>
<pre>
# coding: Shift_JIS

import os # osモジュールのインポート

# os.listdir('パス')
# 指定したパス内の全てのファイルとディレクトリを要素とするリストを返す
files = os.listdir('C:\Python25\')

for file in files:
    print file
</pre>
<h3>実行結果の一例</h3>
<pre>
DLLs
Doc
include
Lib
libs
LICENSE.txt
lxml-wininst.log
NEWS.txt
PIL-wininst.log
pysqlite-wininst.log
pysqlite2-doc
python.exe
pythonw.exe
README.txt
Removelxml.exe
RemovePIL.exe
Removepysqlite.exe
Scripts
tcl
Tools
w9xpopen.exe
</pre>
<h2>ワイルドカードでリスティング対象を指定</h2>
<p>globモジュールのglob()関数の引数内にワイルドカード「*」を含めることが出来ます。これによって、より手軽に目的のファイルを探索することが出来ます。</p>
<h3>ソースコード</h3>
<pre>
# coding: Shift_JIS

import glob

# パス内の全ての"指定パス+ファイル名"と"指定パス+ディレクトリ名"を要素とするリストを返す
files = glob.glob('C:\Python25\*.*') # ワイルドカードが使用可能

for file in files:
    print file
</pre>
<p>os.listdir()と異なり、glob.glob()は取得したファイル文字列には先頭に探査ディレクトリ(引数)のパスが付いています。</p>
<h3>実行結果の一例</h3>
<p><code><br />
C:Python25LICENSE.txt<br />
C:Python25lxml-wininst.log<br />
C:Python25NEWS.txt<br />
C:Python25PIL-wininst.log<br />
C:Python25pysqlite-wininst.log<br />
C:Python25python.exe<br />
C:Python25pythonw.exe<br />
C:Python25README.txt<br />
C:Python25Removelxml.exe<br />
C:Python25RemovePIL.exe<br />
C:Python25Removepysqlite.exe<br />
C:Python25w9xpopen.exe<br />
</code></p>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/module-glob.html" title="11.7 glob -- Unix style pathname pattern expansion" target="_blank">11.7 glob &#8212; Unix style pathname pattern expansion</a></li>
<li><a href="http://docs.python.org/lib/os-file-dir.html" title="14.1.4 Files and Directories" target="_blank">14.1.4 Files and Directories</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/r-set-work-directory.html" rel="bookmark" title="2008年9月3日">Rで統計: 作業ディレクトリの設定と確認 &#8211; setwd()、getwd()関数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/linux-users.html" rel="bookmark" title="2008年6月26日">ユーザー管理に関するLinuxコマンド</a></li>
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html" rel="bookmark" title="2008年12月17日">AIR: テキストファイルを非同期に読み込む &#8211; openAsync()、readMultiByte()</a></li>
</ul>
<p><!-- Similar Posts took 13.734 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html">Python: 指定したパスのディレクトリ中のファイル一覧を出力</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: 正規表現の基本 &#8211; 最長、最短マッチング</title>
		<link>http://www.yukun.info/blog/2008/08/python-regexp-greedy-reluctant-match.html</link>
		<comments>http://www.yukun.info/blog/2008/08/python-regexp-greedy-reluctant-match.html#comments</comments>
		<pubDate>Thu, 07 Aug 2008 15:00:49 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Loop]]></category>
		<category><![CDATA[RegExp]]></category>

		<guid isPermaLink="false">http://trumpcode.yukun.info/?p=368</guid>
		<description><![CDATA[直前の文字、メタ文字を繰り返しマッチングさせる量指定記号である「*」「+」「?」などは、テキスト中にその繰り返しパターンがマッチする箇所が複数ある場合は、通常最後にマッチした箇所をオブジェクトに記録します。このような最長 &#8230; <a href="http://www.yukun.info/blog/2008/08/python-regexp-greedy-reluctant-match.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/08/python-regexp-greedy-reluctant-match.html">Python: 正規表現の基本 &#8211; 最長、最短マッチング</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>直前の文字、メタ文字を繰り返しマッチングさせる量指定記号である「*」「+」「?」などは、テキスト中にその繰り返しパターンがマッチする箇所が複数ある場合は、通常最後にマッチした箇所をオブジェクトに記録します。このような最長マッチングに対して、マッチング箇所が複数の場合に最初にマッチした箇所を記録する最短マッチング方法があります。</p>
<p>最短マッチングを行う量指定記号は最長マッチングの記号の<strong>末尾に「?」を付ける</strong>だけです。すなわち、最長の量指定が「*」「+」「?」であるのに対して、<strong>最短マッチングは「*?」「+?」「??」</strong>となります。それでは、以下のコードで確認してみましょう。</p>
<h3>ソースコード</h3>
<pre>
# coding: Shift_JIS

import re # 正規表現を扱うモジュールのインポート

# 正規表現のチェックプリント用の関数
def PrintRegMatch(pat, txt):
    #   書式: re.search(パターン, テキスト)
    m = re.search(pat, txt) # パターンにマッチしなかった場合はNoneを返す
    if m != None:
        print &#039;パターン: &quot;%s&quot;nテキスト: &quot;%s&quot;nマッチ  : する&#039; % (pat, txt)
        print &#039;マッチング開始位置:&#039;, m.start()
        print &#039;マッチング終了位置:&#039;, m.end()
    else:
        print &#039;パターン: &quot;%s&quot;nテキスト: &quot;%s&quot;nマッチ: しない&#039; % (pat, txt)
    print
    return m

# サンプルテキスト
txt = &#039;&lt;p&gt;Hello! World!!&lt;/p&gt;&lt;p&gt;Goodbye World&lt;/p&gt;&#039;
# 最長: .*
# 最短: .*?
PrintRegMatch(&#039;&lt;p&gt;.*&lt;/p&gt;&#039;,  txt) # 最長: 文字列末尾の&lt;/p&gt;にマッチ
PrintRegMatch(&#039;&lt;p&gt;.*?&lt;/p&gt;&#039;, txt) # 最短: World!!&lt;/p&gt;の&lt;/p&gt;にマッチ

# 最長: .+
# 最短: .+?
PrintRegMatch(&#039;&lt;p&gt;.+&lt;/p&gt;&#039;,  txt) # +?は直前の文字の1文字以上の繰り返し
PrintRegMatch(&#039;&lt;p&gt;.+?&lt;/p&gt;&#039;, txt) # &uarr;の控えめマッチング

# 最長: .?
# 最短: .??
PrintRegMatch(&#039;B.?C&#039;,  &#039;BCCC&#039;)   # ?は直前の文字の0 or 1回の繰り返し
PrintRegMatch(&#039;B.??C&#039;, &#039;BCCC&#039;)   # ??はその控えめ(ry
</pre>
<p>re.searchはre.matchと異なり、パターンを<strong>テキスト文字列の先頭以外</strong>にもマッチさせます。</p>
<h3>実行結果</h3>
<pre>
パターン: &quot;&lt;p&gt;.*&lt;/p&gt;&quot;
テキスト: &quot;&lt;p&gt;Hello! World!!&lt;/p&gt;&lt;p&gt;Goodbye World&lt;/p&gt;&quot;
マッチ  : する
マッチング開始位置: 0
マッチング終了位置: 41

パターン: &quot;&lt;p&gt;.*?&lt;/p&gt;&quot;
テキスト: &quot;&lt;p&gt;Hello! World!!&lt;/p&gt;&lt;p&gt;Goodbye World&lt;/p&gt;&quot;
マッチ  : する
マッチング開始位置: 0
マッチング終了位置: 21

パターン: &quot;&lt;p&gt;.+&lt;/p&gt;&quot;
テキスト: &quot;&lt;p&gt;Hello! World!!&lt;/p&gt;&lt;p&gt;Goodbye World&lt;/p&gt;&quot;
マッチ  : する
マッチング開始位置: 0
マッチング終了位置: 41

パターン: &quot;&lt;p&gt;.+?&lt;/p&gt;&quot;
テキスト: &quot;&lt;p&gt;Hello! World!!&lt;/p&gt;&lt;p&gt;Goodbye World&lt;/p&gt;&quot;
マッチ  : する
マッチング開始位置: 0
マッチング終了位置: 21

パターン: &quot;B.?C&quot;
テキスト: &quot;BCCC&quot;
マッチ  : する
マッチング開始位置: 0
マッチング終了位置: 3

パターン: &quot;B.??C&quot;
テキスト: &quot;BCCC&quot;
マッチ  : する
マッチング開始位置: 0
マッチング終了位置: 2
</pre>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/module-re.html" target="_blank">4.2 re &#8212; Regular expression operations</a></li>
<ul>
<li><a href="http://docs.python.org/lib/re-syntax.html" target="_blank">4.2.1 Regular Expression Syntax</a></li>
<li><a href="http://docs.python.org/lib/re-objects.html" target="_blank">4.2.4 Regular Expression Objects</a></li>
</ul>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/07/python-regular-expression-loop.html" rel="bookmark" title="2008年7月20日">Python: 正規表現の基本 &#8211; 繰り返し「*」「+」「?」</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-regular-expression.html" rel="bookmark" title="2008年7月19日">Python: 正規表現の基本 &#8211; メタ文字「.」「^」「$」</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-regular-expression-range.html" rel="bookmark" title="2008年7月21日">Python: 正規表現の基本 &#8211; 文字範囲の指定「[ ]」</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-string.html" rel="bookmark" title="2008年7月2日">Python: 文字列の検索 &#8211; index()、reindex()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list-comprehension.html" rel="bookmark" title="2008年6月16日">Python: リスト内包表記(リストコンプリヘンション)をfor文に書き換える</a></li>
</ul>
<p><!-- Similar Posts took 11.186 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/08/python-regexp-greedy-reluctant-match.html">Python: 正規表現の基本 &#8211; 最長、最短マッチング</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/08/python-regexp-greedy-reluctant-match.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python: set型の集合演算で2つのリスト要素を比較</title>
		<link>http://www.yukun.info/blog/2008/08/python-set-list-comparison.html</link>
		<comments>http://www.yukun.info/blog/2008/08/python-set-list-comparison.html#comments</comments>
		<pubDate>Wed, 06 Aug 2008 15:00:46 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[Set]]></category>

		<guid isPermaLink="false">http://trumpcode.yukun.info/?p=316</guid>
		<description><![CDATA[2つのリストの要素を比較する際、リスト型をset型に変えると「-」「&#038;」などの演算子1つで集合演算できます(AND、OR、NOTとか)。 ソースコード #!/usr/bin/python # coding: U &#8230; <a href="http://www.yukun.info/blog/2008/08/python-set-list-comparison.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/08/python-set-list-comparison.html">Python: set型の集合演算で2つのリスト要素を比較</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>2つのリストの要素を比較する際、リスト型をset型に変えると「-」「&#038;」などの演算子1つで集合演算できます(AND、OR、NOTとか)。</p>
<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

# リストの比較(by 集合演算)

old_list = ['A', 'B', 'C', 'D', 'E', 'F'] # 古いリスト
new_list = ['A', 'C', 'F', 'G', 'H', 'I'] # 更新された新しいリスト、とする

# 組み込み関数set()を用いて(リストを含む)シーケンス型からset型データを作成
old_set = set(old_list)
new_set = set(new_list)
print 'old_set           ==', old_set
print 'new_set           ==', new_set

# 差集合: old_setの要素からnew_setに含まれる要素を削除した要素集合
# すなわち、old_setをnew_setに更新した際に、削除された要素集合、とみる
print 'old_set - new_set ==', old_set - new_set
print 'len(old_set - new_set) ==', len(old_set - new_set) # 削除された個数

# old_setをnew_setに更新した際に、追加された要素集合、とみる
print 'new_set - old_set ==', new_set - old_set
print 'len(new_set - old_set) ==', len(new_set - old_set) # 追加された個数

# old_setをnew_setの共通要素集合(更新した際に変更されなかった要素、とみる)
print 'new_set &#038; old_set ==', new_set &#038; old_set

# old_setかnew_setに含まれる要素集合
print 'new_set ^ old_set ==', new_set ^ old_set

# 和集合: old_setとnew_setに含まれる重複の無い要素集合
print 'new_set | old_set ==', new_set | old_set
</pre>
<h3>実行結果</h3>
<pre>
old_set           == set(['A', 'C', 'B', 'E', 'D', 'F'])
new_set           == set(['A', 'C', 'G', 'F', 'I', 'H'])
old_set - new_set == set(['B', 'E', 'D'])
len(old_set - new_set) == 3
new_set - old_set == set(['I', 'H', 'G'])
len(new_set - old_set) == 3
new_set &#038; old_set == set(['A', 'C', 'F'])
new_set ^ old_set == set(['B', 'E', 'D', 'G', 'I', 'H'])
new_set | old_set == set(['A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H'])
</pre>
<p>リスト(and シーケンス型)をset型に変更すると要素の順序が失われます。再度リスト型に戻したいときは、list()関数を用います。</p>
<pre>
&gt;&gt;&gt; set_data = set([&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;])
&gt;&gt;&gt; set_data
set([&#039;a&#039;, &#039;c&#039;, &#039;b&#039;, &#039;d&#039;])
&gt;&gt;&gt; list_data = list(set_data)
&gt;&gt;&gt; list_data
[&#039;a&#039;, &#039;c&#039;, &#039;b&#039;, &#039;d&#039;]
&gt;&gt;&gt; type(list_data)
&lt;type &#039;list&#039;&gt;
&gt;&gt;&gt;
</pre>
<p>話変わりますが、Rubyだと配列のまま加減算ができます(配列オブジェクトが「+」「-」演算子などをサポートしているみたい)。</p>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/types-set.html" title="3.7 Set Types -- set, frozenset" target="_blank">3.7 Set Types &#8212; set, frozenset</a></li>
<li><a href="http://docs.python.org/lib/module-sets.html" title="5.7 sets -- Unordered collections of unique elements" target="_blank">5.7 sets &#8212; Unordered collections of unique elements</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/python-list.html" rel="bookmark" title="2008年6月1日">Python: リストの初期化・出力・代入・要素数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list-comprehension.html" rel="bookmark" title="2008年6月16日">Python: リスト内包表記(リストコンプリヘンション)をfor文に書き換える</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-if-for-in.html" rel="bookmark" title="2008年8月2日">Python: if/for文でのin演算子の各オブジェクト毎の評価</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-sequence.html" rel="bookmark" title="2008年6月2日">Python: リストの抽出・連結・要素の追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list2.html" rel="bookmark" title="2008年6月12日">Python: リストの要素の追加と削除、取出し &#8211; append()、extend()、pop()、remove()メソッド</a></li>
</ul>
<p><!-- Similar Posts took 8.339 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/08/python-set-list-comparison.html">Python: set型の集合演算で2つのリスト要素を比較</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/08/python-set-list-comparison.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Python: 文字列の上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</title>
		<link>http://www.yukun.info/blog/2008/08/python-sequence-string.html</link>
		<comments>http://www.yukun.info/blog/2008/08/python-sequence-string.html#comments</comments>
		<pubDate>Tue, 05 Aug 2008 15:00:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Sequence]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://trumpcode.yukun.info/?p=310</guid>
		<description><![CDATA[データの順序が存在するデータ型としてシーケンス型があり、文字列型の上位型となっています。このシーケンス型には文字列中の文字の抽出や操作を簡略化する分かりやすい構文がありますので、これを確認してみましょう。 String[ &#8230; <a href="http://www.yukun.info/blog/2008/08/python-sequence-string.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/08/python-sequence-string.html">Python: 文字列の上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>データの順序が存在するデータ型としてシーケンス型があり、文字列型の上位型となっています。このシーケンス型には文字列中の文字の抽出や操作を簡略化する分かりやすい構文がありますので、これを確認してみましょう。</p>
<h2>String[X:] はString[X]から末尾までの文字を持つ文字列</h2>
<pre>
#!/usr/bin/python
# coding: UTF-8

s = 'abcdefg'
print 's      ', s
print 's[0:]  ', s[0:]
print 's[1:]  ', s[1:]
print 's[-1:] ', s[-1:]
print 's[-5:] ', s[-5:]
</pre>
<h3>実行結果</h3>
<pre>
s       abcdefg
s[0:]   abcdefg
s[1:]   bcdefg
s[-1:]  g
s[-5:]  cdefg
</pre>
<h2>String[:Y] は文字列の先頭からString[Y-1]までの文字を持つ文字列</h2>
<pre>
s = 'abcdefg'
print 's      ', s
print 's[:3]  ', s[:3]  # s[0] s[1] s[2]まで
print 's[:-1] ', s[:-1] # Yは-1よりs[(-1)-1]→s[-2]までの文字列
print 's[:-5] ', s[:-5]
</pre>
<h3>実行結果</h3>
<pre>
s       abcdefg
s[:3]   abc
s[:-1]  abcdef
s[:-5]  ab
</pre>
<h2>String[::Z] は文字列の先頭から末尾まで Z 間隔で文字を抽出した文字列</h2>
<pre>
s = 'abcdefg'
print 's      ', s
print 's[::1] ', s[::1]  # 1間隔なのでsと同じ
print 's[::2] ', s[::2]
print 's[::-1]', s[::-1] # 「-」を付けると逆順に辿っていきます
</pre>
<h3>実行結果</h3>
<pre>
s       abcdefg
s[::1]  abcdefg
s[::2]  aceg
s[::-1] gfedcba
</pre>
<p><strong>文字列の文字順序を逆順にする</strong>処理を構文で賄えるのは良いですね。汎用性があって。</p>
<h2>上述の複合 &#8211; String[X:Y:Z]</h2>
<pre>
s = 'abcdefg'
print 's        ', s
print 's[1:3]   ', s[1:3]
print 's[:-1:2] ', s[:-1:2]
print 's[-1::-2]', s[-1::-2]
print 's[1:4:2] ', s[1:4:2]
</pre>
<h3>実行結果</h3>
<pre>
s         abcdefg
s[1:3]    bc
s[:-1:2]  ace
s[-1::-2] geca
s[1:4:2]  bd
</pre>
<h3>チュートリアル</h3>
<ul>
<li><a href="http://docs.python.org/tut/node7.html" title="5. Data Structures" target="_blank">5. Data Structures</a>
<ul>
<li><a href="http://docs.python.org/tut/node7.html#SECTION007300000000000000000" title="5.3 Tuples and Sequences" target="_blank">5.3 Tuples and Sequences</a></li>
<li><a href="http://docs.python.org/tut/node7.html#SECTION007800000000000000000" title="5.8 Comparing Sequences and Other Types" target="_blank">5.8 Comparing Sequences and Other Types</a></li>
</ul>
</li>
</ul>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/typesseq.html" title="3.6 Sequence Types -- str, unicode, list, tuple, buffer, xrange" target="_blank">3.6 Sequence Types &#8212; str, unicode, list, tuple, buffer, xrange</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/08/python-sequence-list.html" rel="bookmark" title="2008年8月5日">Python: リストの上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-decimal-to-binary-conversion.html" rel="bookmark" title="2008年8月4日">Python: 10進数整数を2進数文字列に変換する関数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-sequence.html" rel="bookmark" title="2008年6月2日">Python: リストの抽出・連結・要素の追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-upper-lower-case-letters-converted.html" rel="bookmark" title="2008年8月3日">Python: リスト中の文字列を大文字⇔小文字に変換</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-string.html" rel="bookmark" title="2008年7月2日">Python: 文字列の検索 &#8211; index()、reindex()メソッド</a></li>
</ul>
<p><!-- Similar Posts took 6.496 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/08/python-sequence-string.html">Python: 文字列の上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/08/python-sequence-string.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: リストの上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</title>
		<link>http://www.yukun.info/blog/2008/08/python-sequence-list.html</link>
		<comments>http://www.yukun.info/blog/2008/08/python-sequence-list.html#comments</comments>
		<pubDate>Mon, 04 Aug 2008 15:00:39 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[Sequence]]></category>

		<guid isPermaLink="false">http://trumpcode.yukun.info/?p=296</guid>
		<description><![CDATA[データの順序が存在するデータ型としてシーケンス型があり、リストの上位型となっています。このシーケンス型には要素の抽出や操作を簡略化する分かりやすい構文がありますので、これを確認してみましょう。 List[X:] はLis &#8230; <a href="http://www.yukun.info/blog/2008/08/python-sequence-list.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/08/python-sequence-list.html">Python: リストの上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>データの順序が存在するデータ型としてシーケンス型があり、リストの上位型となっています。このシーケンス型には要素の抽出や操作を簡略化する分かりやすい構文がありますので、これを確認してみましょう。</p>
<h2>List[X:] はList[X]から末尾までの要素を持つリスト</h2>
<pre>
#!/usr/bin/python
# coding: UTF-8

a = [10, 20, 30, 40, 50]
print 'a      ', a
print 'a[0:]  ', a[0:]
print 'a[1:]  ', a[1:]
print 'a[-1:] ', a[-1:]
print 'a[-5:] ', a[-5:]
</pre>
<h3>実行結果</h3>
<pre>
a       [10, 20, 30, 40, 50]
a[0:]   [10, 20, 30, 40, 50]
a[1:]   [20, 30, 40, 50]
a[-1:]  [50]
a[-5:]  [10, 20, 30, 40, 50]
</pre>
<h2>List[:Y] はListの先頭からList[Y-1]までの要素を持つリスト</h2>
<pre>
a = [10, 20, 30, 40, 50]
print 'a      ', a
print 'a[:3]  ', a[:3]  # a[0] a[1] a[2]まで
print 'a[:-1] ', a[:-1] # Yは-1よりa[(-1)-1]→a[-2]までのリスト
print 'a[:-5] ', a[:-5]
</pre>
<h3>実行結果</h3>
<pre>
a       [10, 20, 30, 40, 50]
a[:3]   [10, 20, 30]
a[:-1]  [10, 20, 30, 40]
a[:-5]  []
</pre>
<h2>List[::Z] はListの先頭から末尾まで Z 間隔で要素を抽出したリスト</h2>
<pre>
a = [10, 20, 30, 40, 50]
print 'a      ', a
print 'a[::1] ', a[::1]  # 1間隔なのでaと同じ
print 'a[::2] ', a[::2]
print 'a[::-1]', a[::-1] # 「-」を付けると逆順に辿っていきます
</pre>
<h3>実行結果</h3>
<pre>
a       [10, 20, 30, 40, 50]
a[::1]  [10, 20, 30, 40, 50]
a[::2]  [10, 30, 50]
a[::-1] [50, 40, 30, 20, 10]
</pre>
<p>リストの<strong>要素順序を逆順</strong>にする処理を構文で賄えるのは良いですね。</p>
<h2>上述の複合 &#8211; List[X:Y:Z]</h2>
<pre>
a = [10, 20, 30, 40, 50]
print 'a        ', a
print 'a[1:3]   ', a[1:3]
print 'a[:-1:2] ', a[:-1:2]
print 'a[-1::-2]', a[-1::-2]
print 'a[1:4:2] ', a[1:4:2]
</pre>
<h3>実行結果</h3>
<pre>
a         [10, 20, 30, 40, 50]
a[1:3]    [20, 30]
a[:-1:2]  [10, 30]
a[-1::-2] [50, 30, 10]
a[1:4:2]  [20, 40]
</pre>
<h3>チュートリアル</h3>
<ul>
<li><a href="http://docs.python.org/tut/node7.html" title="5. Data Structures" target="_blank">5. Data Structures</a>
<ul>
<li><a href="http://docs.python.org/tut/node7.html#SECTION007300000000000000000" title="5.3 Tuples and Sequences" target="_blank">5.3 Tuples and Sequences</a></li>
<li><a href="http://docs.python.org/tut/node7.html#SECTION007800000000000000000" title="5.8 Comparing Sequences and Other Types" target="_blank">5.8 Comparing Sequences and Other Types</a></li>
</ul>
</li>
</ul>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/typesseq.html" title="3.6 Sequence Types -- str, unicode, list, tuple, buffer, xrange" target="_blank">3.6 Sequence Types &#8212; str, unicode, list, tuple, buffer, xrange</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/python-sequence.html" rel="bookmark" title="2008年6月2日">Python: リストの抽出・連結・要素の追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-sequence-string.html" rel="bookmark" title="2008年8月6日">Python: 文字列の上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list.html" rel="bookmark" title="2008年6月1日">Python: リストの初期化・出力・代入・要素数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list2.html" rel="bookmark" title="2008年6月12日">Python: リストの要素の追加と削除、取出し &#8211; append()、extend()、pop()、remove()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-set-list-comparison.html" rel="bookmark" title="2008年8月7日">Python: set型の集合演算で2つのリスト要素を比較</a></li>
</ul>
<p><!-- Similar Posts took 16.090 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/08/python-sequence-list.html">Python: リストの上位型であるシーケンス型の構文 &#8211; Sequence[X:Y:Z]</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/08/python-sequence-list.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

