Skip to main content

75 posts tagged with "Python"

View All Tags

Python: 可変個の引数を受け取る関数

· One min read
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

# 可変個の引数を受け取る関数 # 引数の前に*を付けると、関数内ではタプルとして受け取る def sigma_sq(*nums): # Σf(k)^xのを計算、f(n)はnumsの要素 print (type(nums), nums) x = 2 # 乗数 n_elem = len(nums) # タプルの長さ sum = 0 for elem in nums: sum += pow(elem, x) # x乗する return sum

print(sigma_sq(1, 2, 3)) # 関数呼び出し側の引数: リスト[タプル]の前に*を付けると # 関数側でリスト[タプル]を展開し、個々の要素を埋め込んでくれる list = [1, 2, 3] print(sigma_sq(*list)) print(sigma_sq(*[x for x in range(4)])) def plusx3(a, b, c): return a+b+c print ('n', plusx3(*list)) # 補足: 上の処理を簡潔に書く sq = 2 print ('n', sum([pow(x, sq) for x in list]))

実行結果

(1, 2, 3)
14
(1, 2, 3)
14
(0, 1, 2, 3)
14
n 6
n 14

チュートリアル

Python: CSVファイルに書き込み - csv.writerオブジェクト

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

試しにチャット履歴をCSVファイルに保存するという場合の例を取り上げます。まぁ実際はメッセンジャーアプリのXMLファイル等をコンバートして保存する例を持ってきた方が良いのかもしれませんが、そうするとコードが長くなり今記事の焦点が合わなくなるので割愛します。

ソースコード

#!/usr/bin/python
# coding: UTF-8
# CSVファイルに書き込み
import csv # CSVファイルを扱うためのモジュールのインポート
filename = "table02.csv"
writecsv = csv.writer(file(filename, 'w'), lineterminator='n') # 書き込みファイルの設定
writecsv.writerow(['2007/11/12 20:19:18', 'や、こんばんは。']) # 1行(リスト)の書き込み
writecsv.writerow(['2007/11/12 20:19:39', 'おいーす'])
writecsv.writerow(['2007/11/12 20:19:53', '久しぶりだね'])
writecsv.writerow(['2007/11/12 20:20:02', 'そだね。'])
chatable = [['2007/11/12 20:42:58', 'そうだね'],
['2007/11/12 20:43:03', '色々ありがとう'],
['2007/11/12 20:43:12', 'いえ、こちらこそ。'],
['2007/11/12 20:43:21', 'それじゃあまた'],
['2007/11/12 20:43:27', 'うん、またねー。']]
writecsv.writerows(chatable) # 複数行(リストのリスト|テーブル)の書き込み

実行結果 (table02.csv)

2007/11/12 20:19:18,や、こんばんは。
2007/11/12 20:19:39,おいーす
2007/11/12 20:19:53,久しぶりだね
2007/11/12 20:20:02,そだね。
2007/11/12 20:42:58,そうだね
2007/11/12 20:43:03,色々ありがとう
2007/11/12 20:43:12,いえ、こちらこそ。
2007/11/12 20:43:21,それじゃあまた
2007/11/12 20:43:27,うん、またねー。

リファレンス

Python: CSVファイルの読み込み - csv.readerオブジェクト

· One min read
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

#!/usr/bin/python
# coding: UTF-8
# CSVファイルの読み込み
import csv
filename = "table01.csv"
csvfile = open(filename)
print csvfile
for row in csv.reader(csvfile):
print row # 1行のリスト
for elem in row:
print elem, # 行の中の要素
print
csvfile.close()
print csvfile

CSVファイル (table01.csv) (番号,名前)

1,aki
2,hiro
3,norika
4,kaede

実行結果

<open file 'table01.csv', mode 'r' at 0x01BECCC8>
['1', 'aki']
1 aki
['2', 'hiro']
2 hiro
['3', 'norika']
3 norika
['4', 'kaede']
4 kaede
<closed file 'table01.csv', mode 'r' at 0x01BECCC8>

リファレンス

Python: リスト内包表記(リストコンプリヘンション)をfor文に書き換える

· 3 min read
Yu Sasaki
Enterprise Security Manager / Advisor

リスト内包表記を知ることでコードのリーディングとライティングを早めることが出来ます(パフォーマンスもfor文より良いです)。そこでリスト内包表記とfor文の書き換え方を以下に紹介。

ソースコード

#!/usr/bin/python
# coding: UTF-8
# リスト内包表記(リストコンプリヘンション)をfor文に書き換える
# List Comprehensions
print [a for a in range(10)]
# 0~9の数値を要素とするリスト
a2 = []
for i in range(10):
a2.append(i)
print a2
print [b*2 for b in range(10)] # ループのパラメータに演算を行う
# 0~9の数値の×2の結果を要素とするリスト
b2 = []
for i in range(10):
b2.append(i*2)
print b2
print [c for c in range(10) if c % 2 == 1] # 条件を指定してリストを生成
# in の被演算子を評価後、取り出された要素cをif文にかける。if文が偽のときは、とばして次のループに入る
# 結果として、0~9の数値の中で条件「c % 2 == 1」を満たす、すなわち奇数を要素とするリスト
c2 = []
for i in range(10):
if (i % 2 == 1):
c2.append(i)
print c2
print '\n', b2
print [d+1 for d in b2]
d2 = []
for i in b2:
d2.append(i+1)
print d2
e = 'It is important to set my aims but at the same time I should confirm my present condition.'
print '\n', e
print [wd for wd in e.split(' ')]
e2 = []
for i in e.split(' '):
e2.append(i)
print e2

実行結果

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
It is important to set my aims but at the same time I should confirm my present condition.
['It', 'is', 'important', 'to', 'set', 'my', 'aims', 'but', 'at', 'the', 'same', 'time', 'I', 'should', 'confirm', 'my', 'present', 'condition.']
['It', 'is', 'important', 'to', 'set', 'my', 'aims', 'but', 'at', 'the', 'same', 'time', 'I', 'should', 'confirm', 'my', 'present', 'condition.']

一般化

[新しいリストに格納する要素(*1) for OLD_ELEMENT in OLD_LIST if 条件式] *1: 式を書く

追記(2008-6-17): 文字列の1文字ごとの処理

>>> str = 'hello! hello!'
>>> ' '.join([c.upper() for c in str])
'H E L L O ! H E L L O !'
>>>

ここでの処理内容は、upper()メソッドによる英小文字→大文字の変換です。

チュートリアル

Python: lxmlのインストール方法

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

lxml とはXMLやHTMLを扱うPythonのライブラリの一つです。

lxml is the most feature-rich and easy-to-use library for working with XML and HTML in the Python language. - lxmlの冒頭の文より

linux系OS(Fedoraなど)の場合

# yum python-lxml

も一つの手ですがバージョンが古いので、通常はeasy_install経由でlxmlをインストールします。 前段階として、easy_installをインストールするためにhttp://peak.telecommunity.com/dist/ez\_setup.pyをダウンロードしてスーパーユーザで実行します。

# python ez_setup.py error: invalid Python installation: unable to open /usr/lib/python2.5/config/Makefile (No such file or directory)

上のようなエラーがでた場合はpython-develをインストールします。また、合わせてlxmlに必要なパッケージもインストールするには以下のようなコマンドを実行します。

# yum install python-devel libxml2* libxslt*

改めて、

# python ez_setup.py

完了後、easy_installコマンドが実行できるようになります。 lxmlのインストールは以下のコマンドを実行すればOKです。

# easy_install lxml

ライブラリの確認方法は、

$ python
>>> import lxml
>>>

でエラーが出なければOKです。

アンインストール方法

以下のコマンドを実行。

# easy_install -mxN lxml

Windowsの場合

Webアプリのデプロイ環境はLinux系だけれど、開発やテストの一部はWindows機で行いたいのでWindowsにeasy_installでインストールしようとしましたが、途中でエラーが出て中々上手くいきませんでした。 解決に時間が掛かりそうだったので、とりあえずPython Package Index : lxml 1.3.4のlxml-1.3.4.win32-py2.5.exeをダウンロード&インストールして済ませました。

参考にした記事

Python: リストの要素の追加と削除、取出し - append()、extend()、pop()、remove()メソッド

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

#!/usr/bin/python
# coding: UTF-8
# リストの要素の追加と削除(取出し) | append()、extend()、pop()、remove()メソッドの使い方
a = [3, 5, 7, 9, 11]
print a
a.append(13) # 引数のオブジェクトをリストの末尾に追加
print a
a.extend([15, 17, 19, 21]) # 引数のシーケンスを展開して末尾に追加
print a
elm = a.pop() # リストの末尾から要素を1つ取り出す
print 'elm == %d' % elm
print a
elm = a.pop(4) # 引数にリストのインデックスを取り、その要素を取り出す
print 'elm == %d' % elm
print a
a.remove(13) # 引数のオブジェクトをリスト要素から削除する
print a

実行結果

[3, 5, 7, 9, 11]
[3, 5, 7, 9, 11, 13]
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
elm == 21
[3, 5, 7, 9, 11, 13, 15, 17, 19]
elm == 11
[3, 5, 7, 9, 13, 15, 17, 19]
[3, 5, 7, 9, 15, 17, 19]

リファレンス

チュートリアル

Python: モジュールにテスト関数を定義 - 重複のない乱数(整数MIN以上MAX以下)の生成

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

#!/usr/bin/python
# coding: UTF-8
import random
def make_randint_list(min, max, cnt, sortflag=False, revflag=False):
"""
重複のない乱数(整数min以上max以下)を要素としたリストを返す
"""
list = []
i = 0
while cnt != i:
r = random.randint(min, max)
try:
list.index(r) # 既にリストに存在するか
except ValueError, e:
list.append(r) # 無い場合はリストに格納
i = i + 1
if (sortflag): list.sort(reverse=revflag)
return list
def _main():
"""モジュールのチェック関数"""
print 'makerand0.py [_main()]'
print make_randint_list(10, 99, 10)
print make_randint_list(10, 99, 10, True) # 昇順ソート
print make_randint_list(10, 99, 10, True, True) # 降順ソート
if __name__ == '__main__' : _main()
#

モジュール変数__name__の中には通常はモジュール名が入っています。しかし、このモジュールファイルを直接実行した場合は__name__に'__main__'という名前が入ります。その為、if __name__ == '__main__' : は真となり_main()が実行されます。

実行結果

$ python makerand0.py
makerand0.py [_main()]
[62, 18, 55, 44, 97, 67, 87, 16, 59, 43]
[11, 13, 30, 42, 46, 52, 71, 75, 81, 92]
[88, 81, 65, 60, 57, 53, 41, 34, 27, 23]

モジュールテスト用スクリプト

makerand0_test.py

#!/usr/bin/python
# coding: UTF-8
from makerand import make_randint_list
print make_randint_list(10, 99, 10)
print make_randint_list(10, 99, 10, True)
print make_randint_list(10, 99, 10, True, True)

実行結果

$ python makerand0_test.py
[52, 44, 63, 61, 50, 66, 88, 45, 99, 57]
[15, 26, 29, 53, 56, 69, 89, 91, 94, 95]
[96, 95, 93, 88, 79, 75, 64, 62, 33, 11]

リファレンス

チュートリアル

Python: 乱数の生成 - random()、randint()、uniform()、seed()メソッド

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

#!/usr/bin/python
# coding: UTF-8
# 乱数の生成 | random()、randint()、uniform()、seed()メソッドの使い方
import random # モジュールのインポート
print random.random(), 'n' # 0.0 ≦ F < 1.0 の浮動小数点数をランダムに返す
# randint(x, y)メソッド: 整数x以上y以下(x ≦ N ≦ y)の乱数を返す
for i in range(10):
print random.randint(10, 20), ' ',
print 'n'
# uniform(x, y)メソッド: 実数x以上y未満(x ≦ N < y)の乱数を返す
for i in range(10):
print random.uniform(10, 20)
print
# seed()メソッド: 乱数の種の初期化
# (省略した場合はシステムの現在時刻で初期化が行われる)
random.seed(1) # 明示的に初期化
for i in range(10):
print random.randint(10, 20), ' ',
print 'n'
random.seed(1) # もう一度初期化(結果は上と同じとなる)
for i in range(10):
print random.randint(10, 20), ' ',
print 'n'

実行結果

0.610071743263
16 16 15 11 19 16 10 11 20 18
12.8745815718
10.3223430071
10.9674507421
17.5459589302
16.0796539779
15.0854025011
18.6344006559
11.049275088
16.6396732404
12.0720922586
11 19 18 12 15 14 17 18 11 10
11 19 18 12 15 14 17 18 11 10

リファレンス

Python: テキストファイルの読み込み - read()、readlines()、readline()メソッド

· 3 min read
Yu Sasaki
Enterprise Security Manager / Advisor

以下の読み込み用テキストファイルを用いて、 text.txt

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.

以下のメソッドを用いた場合の処理を書いてみます。

  • read() - ファイルを全て読み込み、その文字列データに対して処理を行う
  • readlines() - ファイルを全て読み込み、1行毎に処理を行う
  • readline() - 1行毎に読み込み、その処理を繰り返す

read() - ファイルを全て読み込み、その文字列データに対して処理を行う

f = open('text.txt')
data1 = f.read() # ファイル終端まで全て読んだデータを返す
f.close()
print(type(data1)) # 文字列データ
lines1 = data1.split('\n') # 改行で区切る(改行文字そのものは戻り値のデータには含まれない)
print(type(lines1))
for line in lines1:
print line
print()

実行結果


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.

readlines() - ファイルを全て読み込み、1行毎に処理を行う

f = open('text.txt')
lines2 = f.readlines() # 1行毎にファイル終端まで全て読む(改行文字も含まれる)
f.close()
# lines2: リスト。要素は1行の文字列データ
for line in lines2:
print(line),
print

実行結果

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.

readline() - 1行毎に読み込み、その処理を繰り返す

f = open('text.txt')
line = f.readline() # 1行を文字列として読み込む(改行文字も含まれる)
while line:
print(line)
line = f.readline()
f.close

実行結果

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 Ishould do from now on.

リファレンス

チュートリアル

Python: 現在の日付・時刻の取得と出力 - datetimeクラスの属性、today()、strftime()メソッド

· 2 min read
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

#!/usr/bin/python
# coding: UTF-8
# 現在の日付・時刻の取得と出力 | datetimeクラスの属性、today()、strftime()メソッドの使い方
import datetime # datetimeモジュールのインポート
import locale # import文はどこに書いてもOK(可読性などの為、慣例でコードの始めの方)
# today()メソッドで現在日付・時刻のdatetime型データの変数を取得
d = datetime.datetime.today()
# ↑モジュール名.クラス名.メソッド名
print 'd == %s : %s\n' % (d, type(d)) # Microsecond(10^-6sec)まで取得
# datetime型の各属性へのアクセス
# year, month, day
print '%s年%s月%s日\n' % (d.year, d.month, d.day)
# hour, minute, second, microsecond
print '%s時%s分%s.%s秒n' % (d.hour, d.minute, d.second, d.microsecond)
# strftime()メソッドで日付時刻の書式を指定して出力
print d.strftime("%Y-%m-%d %H:%M:%S"), '\n'
# 地域の設定
locale.setlocale(locale.LC_ALL, 'ja') # 属性の出力に影響(曜日とか)
print locale.getlocale(), '\n'
print d.strftime("%B%d日%A") # locale.setlocale()でlocale指定してないと"Fri"と表示(デフォルトの設定地域)
print d.strftime("%p") # 指定の地域でのAM/PMの対応する文字列
print d.strftime("%x %X") # 日付と時刻に対応する文字列

実行結果

d == 2008-06-06 11:50:25.964000 : <type 'datetime.datetime'>
2008年6月6日
11時50分25.964000秒
2008-06-06 11:50:25
('Japanese_Japan', '932')
6月06日金曜日
午前
2008/06/06 11:50:25

リファレンス

チュートリアル